The Programmers Guide To Kotlin - Exceptions
Written by Mike James   
Thursday, 30 July 2020
Article Index
The Programmers Guide To Kotlin - Exceptions

And Finally

You can also add a finally block at the end, and this contains code that will always be executed no matter what happens. The finally block is an important facility because it can be used to remove resources that might have been created. The classic example is to use a finally block to close all the files that might have been opened.

Notice that a finally block is called whether or not an exception has occurred. As a result it is sometimes useful to have a try block with a finally and no catch blocks.

For example:

 do lots of things
finally{  clean up after doing lots of things }

A finally block will be executed, even if the try block contains a return that ends the function.

One big difference between Java and Kotlin is that the try block is actually an expression. Its value is the last expression in the try or the catch that is executed. It is also worth pointing out that the try block is a nested block and hence any variables you might declare within it are local to that block.

So for example:

    var result=a/b

in this case result isn't available outside of the try block. However, as try is an expression:

var result=try{
    a/b }
catch(e:ArithmeticException){   0 }

you can access the result of the division in the main program and the result is zero if an exception occurs. If the try or catch block doesn't return a value then the expression evaluates to Unit.

Another big difference between Kotlin and Java exceptions is that Kotlin doesn't have checked exceptions. Put simply, a checked exception is one that you have to handle and the compiler does a compile-time check to make sure you have. This seemed like a good idea when it was first introduced into Java, but it resulted a great many catch clauses that didn't do anything - either because there was no time to create something meaningful or the programmer knew that an exception of the type was logically impossible.

You can argue about the usefulness of checked exceptions, but Kotlin doesn't have them.

You can create your own exceptions by creating a subclass of Throwable or one of the existing exception classes. To throw an exception all you have to do is create an instance of the exception class and use it in a throw statement:

throw myException()

You can throw an exception from within an exception handler, i.e. a try or catch block, and this is a common way of passing exceptions to other handlers.

Just as try is an expression, so is throw, but it returns the Nothing type. Of course, a throw doesn't allow execution to continue, so it might seem strange to have a value at all. The only point of throw returning Nothing is that it allows it to be included in expressions, i.e. the compiler doesn't complain if you write things like:

val ?: throw myException()

This either assigns myVal a non null value, or it throws an exception and stops the evaluation.

The big problem with exception handling is the cost of implementing anything that works reasonably well from the user’s point of view. Every task within a program should be protected by an exception handler that attempts to recover the situation. This can increase the amount of code needed by a factor of at least ten. While it is difficult to write a program that works when everything goes according to plan, it is next to impossible to write one that still works when things start to go wrong.

Exceptions are a good idea, rarely used sufficiently.





  • An exception is an error or a fault condition that is difficult to test for before it happens.

  • Exceptions allow you to unwind the call stack to get back to an earlier condition that represents things before the error occurred so that you can have another attempt.

  • In Kotlin exceptions are handled using a try catch block:

  • You can also add a finally block at the end, and this contains code that will always be executed no matter what happen.

  • The try block is an expression that returns the value of the last expression in the try or catch.

  • There are no checked exceptions in Kotlin.

  • You can throw your own exceptions using the throw command.

This article is an extract from: 

Programmer's Guide To Kotlin Third Edition


You can buy it from: Amazon


  1. What makes Kotlin Special
  2. The Basics:Variables,Primitive Types and Functions 
  3. Control
         Extract: If and When 
  4. Strings and Arrays
  5. The Class & The Object
  6. Inheritance
  7. The Type Hierarchy
  8. Generics
  9. Collections, Iterators, Sequences & Ranges
        Extract: Iterators & Sequences 
  10. Advanced functions 
  11. Anonymous, Lamdas & Inline Functions
  12. Data classes, enums and destructuring
        Extract: Destructuring 
  13. Exceptions, Annotations & Reflection
  14. Coroutines
        Extract: Coroutines 
  15. Working with Java
        Extract: Using Swing
  16. Compose Multiplatform
        Extract: Compose Layout ***NEW!


To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.


Andrew Tanenbaum Gains ACM Award

Andrew Tanenbaum has been awarded the 2023 ACM System Software Award for MINIX the operating system he created for teaching purposes and which was an important influence on Linux.

Fluid Framework 2 Now Production Ready

Fluid Framework 2, Microsoft's development platform for collaborative ways to work with documents, is now production ready, according to Microsoft.

More News

kotlin book



or email your comment to:



Last Updated ( Monday, 03 August 2020 )