|The documentation for Kotlin is now located on the new site. This page is kept for historical reasons|
All exception classes in Kotlin are descendants of the class Exception. Every exception has a message, stack trace and an optional cause.
To throw an exception object, one uses the throw expression:
To catch an exception, one uses the try expression:
As usual, there may be zero or more catch blocks, and finally may be omitted, but at least one catch or finally must be present.
Note that try is an expression, i.e. it may have a value:
The "returned" value of try expression with no finally is either the last expression in the try block or the last expression in the catch block (or blocks).
If finally block is present, its last expression is the value of try expression.
Why Kotlin has no checked exceptions
People with Java background may wonder why Kotlin does not have checked exceptions. There's so much said on this topic, that we just provide a few citations and one example here.
Our example is java.lang.Appendable – an interface from JDK, implemented by StringBuilder, that has, among others, the following method declaration:
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:
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's checked exceptions were a mistake (Rod Waldhoff)
- The Trouble with Checked Exceptions (Anders Hejlsberg]
Some details on Java interoperability are available here.