Runtime vs checked exceptions

Runtime vs checked exceptions #

Runtime exceptions #

In Java, the simplest exceptions are the instances of the native class RuntimeException. These are also called unchecked exception.

An unchecked exception that is not caught is automatically rethrown.

The class RuntimeException has several native subclasses. You may be familiar wit some of them: NullPointerException, ArrayIndexOutOfBoundsException, IllegalArgumentException, etc.

Checked exceptions #

In Java, an Exception that is not a RuntimeException is called a checked exception.

For instance, an IOException is a checked exception.

A checked exception is not rethrown by default. Instead, it must be explicitly rethrown (or caught), otherwise the program does not compile.

For instance, the following code does not compile, because the method of Files.readAllLines may throw an IOException.

void someMethod(Path path) {
    Files.readAllLines(path);
}

Rethrow explicitly #

This can be fixed by either catching the exception, or explicitly rethrowing it, as follows:

void someMethod(Path path) throws IOException {
    Files.readAllLines(path);
}

Then a method that calls someMethod will in turn have to catch the exception, or rethrow it explicitly, etc.

Warning. Checked exceptions add boilerplate code to method signatures (e.g. throws IOException in the above example). For this reason, it is often recommended to use unchecked exceptions (i.e. instances of RuntimeException) by default. In Effective java (Item 71), Joshua Bloch suggests checked exceptions only if some calling method is likely to catch the exception and take a meaningful action when this happens.