Checked vs. Unchecked Exceptions

While the concept of checked exceptions is not unique to Java, it is a feature most commonly associated with that language. In Java, a checked exception is declared as part of a method, which indicates what sorts of exceptions it might throw:

public void doSomethingPotentiallyTroublesome(File f) throws FileNotFoundException {
  if (!f.exists()) throw new FileNotFoundException(f.getAbsolutePath()+" does not exist!");

  // TODO other stuff, now that we have a valid value
}

Callers of a method that throws checked exceptions must handle those exceptions somehow, either by exposing those exceptions as part of their own method or by catching them and doing something, such as throwing some type of a RuntimeException, as those are unchecked exceptions:

public void troublesomeWrapper(File f) {
  try {
    doSomethingPotentiallyTroublesome(f);
  }
  catch (FileNotFoundException e) {
    throw new IllegalStateException("I'm in a bad state", e);
  }
}

Checked exceptions have been debated a lot over the years. It appears that the consensus opinion is that checked exceptions were an interesting idea that caused more problems than they were worth.

As a result, Kotlin does not offer checked exceptions. Instead, Kotlin treats all exceptions as unchecked, which is the approach taken by many other programming languages.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.