Edit Page

Exceptions

Exception Classes

All exception classes in Kotlin are descendants of the class Throwable. Every exception has a message, stack trace and an optional cause.

To throw an exception object, use the throw-expression

throw MyException("Hi There!")

To catch an exception, use the try-expression

try {
  // some code
}
catch (e: SomeException) {
  // handler
}
finally {
  // optional finally block
}

There may be zero or more catch blocks. finally blocks may be omitted. However at least one catch or finally block should be present.

Try is an expression

try is an expression, i.e. it may have a return value.

val a: Int? = try { parseInt(input) } catch (e: NumberFormatException) { null }

The returned value of a try-expression is either the last expression in the try block or the last expression in the catch block (or blocks). Contents of the finally block do not affect the result of the expression.

Checked Exceptions

Kotlin does not have checked exceptions. There are many reasons for this, but we will provide a simple example.

The following is an example interface of the JDK implemented by StringBuilder class

Appendable append(CharSequence csq) throws IOException;

What does this signature say? It says that every time I append a string to something (a StringBuilder, some kind of a log, a console, etc.) I have to catch those IOExceptions. Why? Because it might be performing IO (Writer also implements Appendable)… So it results into this kind of code all over the place:

try {
  log.append(message)
}
catch (IOException e) {
  // Must be safe
}

And this is no good, see Effective Java, Item 65: Don’t ignore exceptions.

Bruce Eckel says in Does Java need Checked Exceptions?:

Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result – decreased productivity and little or no increase in code quality.

Other citations of this sort:

Java Interoperability

Please see the section on exceptions in the Java Interoperability section for information about Java interoperability.