1. finally: “cleanup” that happens in any scenario
When you write a program, you almost always mentally expect an “ideal world”: the user enters correct data, computations run, we print the result, and we exit the stage nicely to applause. But the real world is when the user enters -999, then q, then 2147483648, and then gets offended that the program “can’t understand simple things”. The finally block is exactly about making your code finish important actions correctly regardless of whether an error happened or not.
Formally, finally { ... } is a block that always runs: if try completes successfully, if an exception occurs inside try, and even if the exception is caught in catch. This is the classic try/catch/finally construct, and Kotlin describes finally as a block for cleanup—actions that must be performed no matter what.
Imagine an analogy: you’re cooking in the kitchen. It doesn’t matter whether the dish turned out well or you accidentally burned the pasta—you still have to wash the dishes. That’s what finally is: “wash the dishes”, not “fix the pasta”.
Mini skeleton of try/catch/finally
fun main() {
try {
println("try: do something useful")
println(10 / 2) // 5
} catch (e: ArithmeticException) {
println("catch: division error")
} finally {
println("finally: I will run always")
}
}
If you change 10 / 2 to 10 / 0, the line from catch will run, but the line from finally will also run.
try { ... } finally { ... } without catch
Sometimes you don’t need to handle the error right here. You need something else: to guarantee completion of an action, and then let the error “bubble up” and crash the program (or be caught somewhere higher). This looks harsh, but in practice it can be useful even in small console programs: for example, you want to always print “Session ended” at the end, or reset some temporary state, or close some resource.
Kotlin allows using try with a single finally without catch. In this case finally will run, and the exception—if it occurred—will continue living its life (that is, the program will still crash if nobody intercepts it). Kotlin also emphasizes that try must be accompanied by at least catch or finally—a “lonely try” makes no sense.
fun main() {
println("Start")
try {
val a = 10
val b = 0
println(a / b) // ArithmeticException
} finally {
println("Finishing: thanks for testing the program")
}
println("Finish") // will not run
}
Notice an important detail: finally will run, but the line println("Finish") will not. That is, finally does not “heal” the program. It just guarantees that you have time to do the required final action.
finally and return: finally runs, but does not “overwrite” the result
At first, finally may seem like magic: “It always runs, so it can change everything?” No: finally has a different role. Kotlin emphasizes separately that finally always runs, but does not change the result of a try/catch expression (whatever is returned from try or catch will be the result).
This matters because you will soon start writing functions that return a value from try/catch. And you need to understand the model: finally is a “side-effect final ritual”, not “another way to return a value”.
fun divideOrMinusOne(a: Int, b: Int): Int {
try {
return a / b
} catch (e: ArithmeticException) {
return -1
} finally {
println("finally: division attempt finished")
}
}
fun main() {
println(divideOrMinusOne(10, 2)) // finally: division attempt finished
// 5
println(divideOrMinusOne(10, 0)) // finally: division attempt finished
// -1
}
If this is your first time seeing return inside try/catch/finally, don’t be alarmed. The logic is simple: as soon as Kotlin knows what to return, it still executes finally before leaving the function.
2. throw: how to honestly say “you can’t do that”
Up to this point, exceptions behaved like a “natural disaster”: division by zero, bad input—and the program crashes. But a developer is a crafty creature: sometimes we ourselves want to say “this is forbidden by the rules of our program” and stop execution so we don’t continue in an invalid state.
That’s what the throw keyword is for: it explicitly throws an exception. Kotlin shows it as directly as other languages do: throw IllegalArgumentException("...").
A useful mental model for a beginner: throw is not an “error message”, but an emergency stop. You’re not asking the program “please be more careful”, you’re saying: “You can’t go any further, the bridge is gone.”
Example: the function accepts only a positive number
fun parsePositiveInt(text: String): Int {
val n = text.toInt()
if (n <= 0) {
throw IllegalArgumentException("Expected a number > 0, but got: $n")
}
return n
}
Here we don’t “catch” the error. We define the function’s contract: it returns an Int, but only if the number is positive. If not, that’s not a “normal scenario”, but a violation of the function usage rules.
An important nuance: throw is an expression of type Nothing
That sounds scarier than it really is. You have seen the Nothing type before: it means “this expression never returns a value”. Kotlin docs show the classic pattern where throw is convenient as a “hard fallback” in the Elvis operator ?:.
fun fail(message: String): Nothing {
throw IllegalArgumentException(message)
}
fun main() {
val name: String? = null
val nonNullName = name ?: fail("Name is required")
println(nonNullName) // we won't get here
}
For now, treat this as a nice bonus: the compiler understands that after fail(...) execution does not continue, and therefore the types “line up”.
How to choose an exception and write a message
When you first learn about throw, a temptation appears: “Oh! I’ll throw exceptions everywhere.” Don’t rush to turn your code into a minefield. throw is good when you want to protect the meaning of a function: if the input data doesn’t fit, it’s better to stop and say so explicitly.
In learning tasks and small console programs, IllegalArgumentException is most commonly used: this exception literally means “the function argument is invalid”. Kotlin actively uses this type in examples about throw.
An exception message is a note to yourself (and future you). A good message usually contains two parts: what was expected and what was received. Then, when it crashes, you won’t have to guess why the program decided to stop.
fun divideStrict(a: Int, b: Int): Int {
if (b == 0) {
throw IllegalArgumentException("Divisor cannot be 0 (a=$a, b=$b)")
}
return a / b
}
Yes, you could just try to divide and catch ArithmeticException. But sometimes it’s better to validate and throw your own clear exception. There isn’t one single correct answer here—what matters is that the behavior is understandable.
3. Mini app: division with clear behavior
Now for the most practical part: we’ll assemble a small console app that performs one action (division), but does it like an adult: it reads input carefully, checks rules, tells the user what’s wrong, and always prints a final line at the end of the attempt. This is the style that will be very useful later when you start writing input and validation functions (yes, that will be a separate course level—today is just the foundation).
Step 1: read a number or null
fun readIntOrNull(prompt: String): Int? {
print(prompt)
val raw = readln().trim()
return raw.toIntOrNull()
}
Nothing magical here: trim() removes extra spaces, and toIntOrNull() either returns an Int or null.
Step 2: strict division with throw
fun divideStrict(a: Int, b: Int): Int {
if (b == 0) throw IllegalArgumentException("You can't divide by 0")
return a / b
}
This is our “contract”: the divisor 0 is forbidden by the rules, so we explicitly say “you can’t do that”.
Step 3: main — catch the expected error and always finalize
fun main() {
val a = readIntOrNull("Enter a: ")
val b = readIntOrNull("Enter b: ")
try {
if (a == null || b == null) throw IllegalArgumentException("You need to enter two integers")
val result = divideStrict(a, b)
println("a / b = $result") // for example: a / b = 5
} catch (e: IllegalArgumentException) {
println("Input/rule error: ${e.message}")
} finally {
println("Done: computation attempt finished")
}
}
What’s important to notice here (and this is a key skill at this level):
try contains only what can realistically “break” within our logic: rule checks, calling divideStrict(...), and printing the result. If everything succeeds, catch is skipped, but finally still runs. If we throw an IllegalArgumentException (ourselves or from divideStrict), control jumps to catch, and then finally still runs.
Execution flow diagram
When you’re just starting out, it’s easy for try/catch/finally to turn into mush in your head: “where does control jump and what runs?”. A simple flowchart helps. Imagine the program is a train, and an exception is the emergency brake.
flowchart TD
A[Enter try] --> B{Did an exception occur in try?}
B -- no --> C[Execute try code to the end]
B -- yes --> D[Jump to a matching catch]
C --> E[Execute finally]
D --> E[Execute finally]
E --> F{Was the exception handled?}
F -- yes --> G[Continue after try/catch/finally]
F -- no --> H["The exception 'flies' upward; the program may crash"]
This diagram is not about “JVM internals”, but about your everyday practice: understanding why the next line does not run, but finally does.
4. Common mistakes when working with finally and throw
Mistake #1: trying to “handle” an error in finally.
Sometimes a beginner thinks: since finally always runs, you should put “rescue logic” there. But finally is for something else: you don’t fix the problem there, you do cleanup. If you start parsing input or changing important data in finally, the code becomes unpredictable: the error has already happened, and you add another layer of surprises.
Mistake #2: writing finally code that can itself crash.
It sounds like a joke, but in practice it happens all the time: in finally people print something, access a variable that may not have been initialized, or do division “for logging”. As a result, you lose the original cause of the error because a new one gets layered on top. A good finally is usually short, simple, and as reliable as possible.
Mistake #3: using throw as a replacement for normal user-scenario validation.
If the user entered something wrong, that’s most often an expected situation. You can handle it gently: print a message and ask them to try again. throw is more useful for violating function rules (contracts), when continuing execution is genuinely dangerous. At our level it’s fine to throw an exception for “you can’t divide by zero”, but if you start throwing exceptions for every typo, the program will constantly “blow up”.
Mistake #4: throwing an exception without a proper message.
An exception without a message is like a note saying “everything is bad” with no details. Kotlin allows throwing IllegalArgumentException() with no text, but then during debugging you get fewer clues. It’s much better to be specific: what you expected and what you got. In Kotlin’s official examples, that’s exactly how it’s done.
Mistake #5: thinking that finally will “continue the program” after a crash.
finally will run, yes. But if the exception is not caught (or you use try/finally without catch), then after finally execution does not turn back into the normal scenario: the exception will still go upward. Kotlin shows that finally guarantees execution of finalizing code, but does not promise that the program will proceed if the error is not handled.
GO TO FULL VERSION