Exception Handling in Kotlin

Exceptions are a standard way to represent errors in most high-level languages such as Kotlin, Java, Swift, or C++. Thus, you can apply the same concepts of reporting and handling errors in many other languages.

Exception not only provide a way to represent but also to handle errors. This way, they allow you to write more robust code.

In this lesson, you’ll learn the basics of exception handling in Kotlin.

Principles

Exceptions allow you to denote erroneous or unexpected behavior in your code.

More importantly, they allow you to handle that error at a different place than where it occurred. We say that exceptions “bubble up” in your code. This exception bubbling enables you to handle exceptions at a level of abstraction where you are able to take meaningful measures (e.g. to recover from the error, to retry the operation, etc).

For example, I/O (input/output) operations are a common source of exceptions, whether you’re accessing a filesystem, a database, or a network resource.

I/O is a rather low-level operation. In the piece of your code that performs I/O, you likely don’t know how to recover from an error – whether to notify the user, retry the operation, skip the operation, try a fallback resource etc. In fact, if your I/O code did implement such logic, one may argue that it violates the Single Responsibility Principle.

In contrast, more high-level parts of your application should be able to recover from an exception like this, e.g.:

  • If a network service is unreachable, the application will retry 2 more times and otherwise notify the user
  • If a file is not found, the application will initialize it

Hands-On Exception Handling

Kotlin has four keywords that are used in exception handling:

  1. throw: Creates (“throws”) a new exception (i.e., “hey, an error occurred here!”)
  2. try: Wraps a piece of code that may throw an exception in order to react to that exception (i.e., “try running this code please, I’m aware it may throw exceptions”)
  3. catch: Defines which code to run if a particular exception was thrown in the try-block (i.e., “ah yes, I expected such an error, let me handle it”). There may be multiple catch-blocks to handle different types of exceptions.
  4. finally: Defines code to run in any case after the try-block and catch-block(s) (i.e., “I don’t know what happened before but I’ll have to do some cleanups”)

Handling of an exception (catch) may done in a completely different part of your code from where the exception originally occurred (throw).

Code Example

The following listing demonstrates how to throw an exception, how exception bubbling works, and how to handle exceptions:

Get hands-on with 1400+ tech skills courses.