← Back to Core Java Course | Chapter 10: Exception Handling | Lesson 7 of 8

Java Exception Hierarchy

The Throwable Class

Throwable sits at the top of Java's exception hierarchy, with Error and Exception as its two direct subclasses — everything you can throw or catch ultimately descends from it.

Example: The Throwable Class

java
public class Main {
	public static void main(String[] args) {
		Throwable t = new Exception("Something went wrong");
		System.out.println(t.getMessage());
	}
}

Error vs Exception

Error represents serious problems outside your program's control, like OutOfMemoryError, that you generally shouldn't try to catch; Exception represents conditions your code can reasonably anticipate and recover from.

Example: Error vs Exception

java
public class Main {
	public static void main(String[] args) {
		try {
			throw new Exception("Recoverable condition");
		} catch (Exception e) {
			System.out.println("Caught an Exception: " + e.getMessage());
		}
		// Error like OutOfMemoryError generally should not be caught
	}
}

RuntimeException Class

RuntimeException is the superclass of all unchecked exceptions, like NullPointerException and ArithmeticException — these signal programming bugs rather than expected external failures.

Example: RuntimeException Class

java
public class Main {
	public static void main(String[] args) {
		try {
			int[] arr = new int[2];
			System.out.println(arr[5]); // ArrayIndexOutOfBoundsException extends RuntimeException
		} catch (RuntimeException e) {
			System.out.println("Caught: " + e.getClass().getSimpleName());
		}
	}
}

Polymorphism in Exceptions

Because exceptions form a class hierarchy, a catch block written for a supertype (like Exception) will also catch any of its subtypes — so catch order matters: more specific exception types must be listed before broader ones.

Example: Polymorphism in Exceptions

java
public class Main {
	public static void main(String[] args) {
		try {
			throw new NullPointerException("npe");
		} catch (Exception e) { // catches the subtype NullPointerException too
			System.out.println("Caught via supertype: " + e.getMessage());
		}
	}
}

Catching Multiple Exception Levels

You can catch several exceptions at different levels of the hierarchy from a single risky operation, letting you handle a specific known failure precisely while still having a broader catch-all for anything unexpected.

Example: Catching Multiple Exception Levels

java
public class Main {
	public static void main(String[] args) {
		try {
			int[] arr = new int[2];
			System.out.println(arr[5]);
		} catch (ArrayIndexOutOfBoundsException e) { // specific level
			System.out.println("Specific: " + e.getMessage());
		} catch (RuntimeException e) { // broader level
			System.out.println("General: " + e.getMessage());
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.