Exceptions Overview
An exception is an object that represents an error condition — something went wrong while a program was running, and normal execution cannot continue along its usual path. When an exception occurs, Java stops executing the current method and starts unwinding the call stack, looking for code prepared to handle it.
An unhandled exception
public class DivideDemo {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
System.out.println("Before the error");
System.out.println(numbers[5]); // no index 5 — throws an exception
System.out.println("This line never runs");
}
}Before the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 3
at DivideDemo.main(DivideDemo.java:5)Because nothing in this program handles the exception, the JVM prints a stack trace and terminates the program. The exception handling chapters that follow are all about controlling this behavior instead of letting it crash your program.
The Exception Class Hierarchy
Class | Category | Meaning |
Throwable | Root | The superclass of everything that can be thrown or caught |
Error | Serious, unrecoverable | Problems outside your control, e.g. OutOfMemoryError — not meant to be caught |
Exception | Recoverable problems | The branch application code is expected to work with |
RuntimeException | Unchecked (subclass of Exception) | Programming errors — not required to be declared or caught |
Checked exceptions | Checked (other Exception subclasses) | Must be caught or declared — e.g. IOException |
Common Built-In Exceptions
Exception | Typically Thrown When |
NullPointerException | Calling a method or accessing a field on a null reference |
ArrayIndexOutOfBoundsException | Accessing an array index that doesn't exist |
ArithmeticException | Integer division by zero |
ClassCastException | An invalid cast between incompatible types |
NumberFormatException | Parsing text that isn't a valid number, e.g. Integer.parseInt("abc") |
A few of the classics, each on its own
public class CommonExceptionsDemo {
public static void main(String[] args) {
String text = null;
System.out.println(text.length()); // NullPointerException
}
}Reading a Stack Trace
A stack trace lists the chain of method calls active at the moment the exception was thrown, in order from where it was thrown down to where the program started. The most useful line for finding the bug is almost always the first one, especially the line number of your own code.
Anatomy of a stack trace
Exception in thread "main" java.lang.NullPointerException:
Cannot invoke "String.length()" because "text" is null
at CommonExceptionsDemo.main(CommonExceptionsDemo.java:4)Line 1 — the exception type and a message describing what went wrong
"at ClassName.methodName(File.java:LINE)" — exactly where it happened
Additional "at" lines below (when present) show the chain of callers