The exception family tree
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every exception in Java is an object, and every exception class has a fixed place in one family tree. Where a class sits in that tree tells you how serious the problem is, whether the compiler makes you handle it, and which catch blocks can catch it.
Throwable at the top of the tree
Throwable is the parent of every error and exception in Java; it has two branches, Error for serious JVM problems and Exception for problems a program can handle.
Throwable is the class at the top of every exception and error in Java. Only an object of Throwable or one of its subclasses can be used with throw or caught with catch.
Example 1 · Walk up the tree with getSuperclass
import java.io.FileNotFoundException;
public class FamilyTreeDemo { static void printLine(Class<?> type) { StringBuilder line = new StringBuilder(type.getSimpleName()); Class<?> parent = type.getSuperclass(); while (parent != null) { line.append(" -> ").append(parent.getSimpleName()); parent = parent.getSuperclass(); } System.out.println(line); }
public static void main(String[] args) { printLine(NumberFormatException.class); printLine(FileNotFoundException.class); printLine(StackOverflowError.class); }}NumberFormatException -> IllegalArgumentException -> RuntimeException -> Exception -> Throwable -> Object FileNotFoundException -> IOException -> Exception -> Throwable -> Object StackOverflowError -> VirtualMachineError -> Error -> Throwable -> Object
What this code does
NumberFormatException.classis an object that describes the class.getSuperclass()returns the parent class, andnullonce you passObject, which stops the loop.- All three lines meet at
Throwable. The first two pass throughException;StackOverflowErrorgoes throughErrorinstead, a different branch.
Each class in the tree has a parent, which you can get with getSuperclass(). Following the parents upward always ends at Throwable, and then at Object, the parent of every Java class. Throwable also gives every exception the same basic tools: getMessage() for the message text, toString() for the class name plus message, and printStackTrace() for the full report.
throw "Payment failed"; does not compile: a String is not a Throwable. Put the text inside an exception object: throw new IllegalStateException("Payment failed");.Error versus Exception
Error is the branch for serious problems in the JVM itself, such as running out of memory (OutOfMemoryError). Exception is the branch for problems a program can expect and often recover from, such as a missing file or a wrong PIN.
Example 2 · An Exception and an Error side by side
public class ErrorVsExceptionDemo { static int depth(int n) { return depth(n + 1); // never stops: every call needs more stack }
static void describe(Throwable t) { String branch = (t instanceof Error) ? "Error" : "Exception"; System.out.println(t.getClass().getSimpleName() + " is in the " + branch + " branch"); }
public static void main(String[] args) { try { Integer.parseInt("9O"); // letter O, not zero } catch (NumberFormatException e) { describe(e); }
try { depth(1); } catch (StackOverflowError e) { // caught here only to look at it describe(e); } System.out.println("Program still running"); }}NumberFormatException is in the Exception branch StackOverflowError is in the Error branch Program still running
What this code does
Integer.parseInt("9O")fails because of bad input, a normal problem, so the JVM throws anExceptionsubclass.depthcalls itself forever until the call stack is full. The JVM then throwsStackOverflowError, which is anError. It is caught here only to print its branch; real code fixes the endless recursion instead.
A chain of method calls that is too deep gives a StackOverflowError, another Error. Text that is not a number is an Exception too. After an Error, the program usually cannot go on safely. Memory is gone or the call stack is full, and trying again fails the same way. An Exception usually has a sensible answer: show a message, ask again, or use a default.
So the rule of thumb is simple. Programs catch Exception types and leave Error types alone. The lesson on what to catch explains why in detail.
The RuntimeException branch
RuntimeException is a subclass of Exception for mistakes in the program's own logic: using null, a bad index, a wrong cast, dividing by zero. These problems come from the code, so a check in the code usually prevents them.
Example 3 · Five bugs, one branch
import java.util.ArrayList;import java.util.List;
public class RuntimeBranchDemo { static void check(String label, Runnable code) { try { code.run(); System.out.println(label + ": no problem"); } catch (RuntimeException e) { System.out.println(label + ": " + e.getClass().getSimpleName()); } }
public static void main(String[] args) { String name = null; int[] marks = {78, 91, 64}; Object fee = Integer.valueOf(45000); List<String> hostelRooms = new ArrayList<>();
check("name.length()", () -> System.out.println(name.length())); check("marks[3]", () -> System.out.println(marks[3])); check("(String) fee", () -> System.out.println((String) fee)); check("100 / 0", () -> System.out.println(100 / 0)); check("hostelRooms.get(0)", () -> System.out.println(hostelRooms.get(0))); check("marks[2]", () -> System.out.println(marks[2])); }}name.length(): NullPointerException marks[3]: ArrayIndexOutOfBoundsException (String) fee: ClassCastException 100 / 0: ArithmeticException hostelRooms.get(0): IndexOutOfBoundsException 64 marks[2]: no problem
What this code does
- One
catch (RuntimeException e)catches all five problems, because each exception class is a subclass ofRuntimeException. - Each one is a bug a check would prevent:
name != null,i < marks.length,fee instanceof String, a non-zero divisor,!hostelRooms.isEmpty(). The last call has a valid index, so it prints64.
Two more members you will throw yourself are IllegalArgumentException (a method got a bad value) and IllegalStateException (an object is not ready for this action, such as paying a fee twice). The compiler does not force you to catch or declare a RuntimeException. Classes outside this branch, such as IOException, are different: the compiler checks them. That split, checked versus unchecked, is the next lesson.
Where common exceptions sit
Each common exception has one fixed place in the tree. The place tells you two things at once: whether the compiler forces you to handle it, and whether it is a bug to fix or a situation to handle.
Example 4 · Sort any exception into its branch
import java.io.FileNotFoundException;import java.io.IOException;import java.util.List;import java.util.NoSuchElementException;
public class ClassifyDemo { static String branch(Throwable t) { if (t instanceof Error) { return "Error"; } else if (t instanceof RuntimeException) { return "RuntimeException"; } else { return "Exception (not runtime)"; } }
public static void main(String[] args) { List<Throwable> samples = List.of( new FileNotFoundException("marks.csv"), new IOException("disk full"), new InterruptedException("download stopped"), new NumberFormatException("12a"), new IllegalStateException("fee already paid"), new NoSuchElementException("no next token"), new OutOfMemoryError("test object only"));
for (Throwable t : samples) { System.out.printf("%-24s %s%n", t.getClass().getSimpleName(), branch(t)); } }}FileNotFoundException Exception (not runtime) IOException Exception (not runtime) InterruptedException Exception (not runtime) NumberFormatException RuntimeException IllegalStateException RuntimeException NoSuchElementException RuntimeException OutOfMemoryError Error
What this code does
- The order of the checks matters. A
RuntimeExceptionis also anException, so the child branch is tested before the general case, or every runtime exception would land in the wrong group. - Creating an
OutOfMemoryErrorwithnewis harmless: it is just an object. Memory runs out only when the JVM itself throws one.
- Under
Error:OutOfMemoryErrorandStackOverflowError(both throughVirtualMachineError),AssertionError. - Under
Exceptiononly:IOExceptionand its childrenFileNotFoundExceptionandEOFException,InterruptedException,SQLException. - Under
RuntimeException:NullPointerException,ArithmeticException,ClassCastException,IllegalStateException, andIllegalArgumentExceptionwith its childNumberFormatException. - Also under
RuntimeException:IndexOutOfBoundsException(children:ArrayIndexOutOfBoundsException,StringIndexOutOfBoundsException) andNoSuchElementException(child:InputMismatchException).
catch for a parent class also catches every child below it. catch (IllegalArgumentException e) catches a NumberFormatException too.Next step
Check your understanding
12 quick questions