Java Exception Hierarchy
In this page:
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
public class Main {
public static void main(String[] args) {
Throwable t = new Exception("Something went wrong");
System.out.println(t.getMessage());
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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());
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: