Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 50 / 68

Cleanup Logic with try/catch/finally

In this lesson you will learn to write cleanup logic with try/catch/finally in Kotlin, so certain work always runs whether or not an error occurred. This is for anyone searching for "Kotlin try catch finally how to use".

A finally block is a cleanup block that always runs, whether an exception was thrown or not. Use it to close files or announce that processing has finished.

The sample code catches a divide-by-zero error inside divide() with catch, and always prints "Ending the calculation" from the finally block regardless of whether anything failed. Notice the Int? return type, which also allows returning null when there is no value.

A common stumbling block for beginners is when finally actually runs. Be careful: a return inside finally overwrites the value the try block was going to return.

In real-world development finally is common wherever an external resource such as a file or a database connection must be closed reliably, whether the work succeeded or failed.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)