Unchecked exceptions in Java

The main pattern that we have been discussing so far applies to checked exceptions, or exceptions whose flow is explicitly "controlled". The basic pattern is that a method declares that a method can throw a given exception, and the caller to that method must explicitly handle the exception (or 'throw it up' to the next caller up the chain).

Some exceptions are actually what are called unchecked exceptions. In our discussion of the exception hierarchy, we mentioned that these are (a) RuntimeExceptions: things like NullPointerException that could pretty much occur 'at any time' due to a programming error; and (b) Errors: serious errors that we basically don't expect to deal with except "in emergency", such as OutOfMemoryError.

How unchecked exceptions differ from regular exceptions

Unchecked exceptions behave as follows:

What happens when an unchecked exception occurs

An uncaught exception is an (unchecked) exception that isn't caught in a try/catch block. We'll take both a simplistic view of how uncaught exceptions are handled and then a more detailed and correct view, because the detailed version can be quite complex (and knowing it all is unnecessary) if you're a beginner to Java.

The simplistic view

When an unchecked exception occurs, what you will see in practice in a simple single-threaded program is that Java prints out the stack trace of the exception and then terminates the program. For example, if we run the following program:

public class TestExceptions {
  public static void main(String[] args) {
    String str = null;
    int len = str.length();
  }
}

we'll get output such as the following:

Exception in thread "main" java.lang.NullPointerException
	at test.TestExceptions.main(TestExceptions.java:4)

In a GUI-driven program, where the exception occurs in an event handler (e.g. in response to a mouse click), the exception stack trace will be printed as above, but the program won't quit.

In certain environments, e.g. mobile phones, Servlets, the system may take some other action, such as indicating to the user with the phone's default message box that an error has occurred.

Details of how uncaught exceptions are handled

Java actually looks for and calls an appropriate uncaught exception handler depending on the thread in which the uncaught exception occurred. On the next page, we'll look at details of how uncaught exception handlers work, and how you can override the default handler.


If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.