Exception Class Hierarchy
Part of the Object Oriented Programming section of Coddy's Java journey — lesson 59 of 87.
Java's exception handling system is built on a well-organized class hierarchy rooted in the Throwable class. Understanding this hierarchy helps you catch and handle exceptions more effectively.
At the top sits Throwable, the parent of all exceptions and errors. It has two direct subclasses:
Throwable
├── Error // Serious problems (don't catch these)
└── Exception // Recoverable problems
└── RuntimeException // Unchecked exceptionsError represents serious problems that applications shouldn't try to handle—like OutOfMemoryError or StackOverflowError. These indicate fundamental issues with the JVM itself.
Exception is the branch you'll work with most. It splits into two categories: checked exceptions (direct subclasses of Exception) and unchecked exceptions (subclasses of RuntimeException).
// Common exception classes
Exception
├── IOException // File/network problems
├── SQLException // Database problems
└── RuntimeException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── IllegalArgumentExceptionBecause exceptions are classes, they follow inheritance rules. When you catch a parent exception type, you also catch all its children:
try {
// some code
} catch (Exception e) {
// Catches ALL exceptions (too broad usually)
}try {
// some code
} catch (RuntimeException e) {
// Catches only runtime exceptions and subclasses
}This hierarchy lets you be as specific or general as needed when handling errors, and it's the foundation for creating your own custom exceptions.
Challenge
EasyLet's build an exception analyzer that demonstrates how Java's exception hierarchy works in practice! You'll create a system that catches exceptions at different levels of specificity and reports which type was caught.
You'll organize your code across three files:
ExceptionThrower.java: Create a class that can trigger different types of exceptions based on input. Your class should have three static methods:triggerRuntime(String type)- Based on the type string, throw different runtime exceptions:- If type is
"null", throw aNullPointerExceptionwith message"Null value encountered" - If type is
"index", throw anArrayIndexOutOfBoundsExceptionwith message"Invalid index" - If type is
"argument", throw anIllegalArgumentExceptionwith message"Bad argument"
triggerArithmetic()- Throw anArithmeticExceptionwith message"Division error"triggerGeneric()- Throw aRuntimeExceptionwith message"Generic runtime error"- If type is
ExceptionAnalyzer.java: Create a class that catches exceptions at different hierarchy levels and identifies what was caught. Include these static methods:analyzeSpecific(String type)- CallExceptionThrower.triggerRuntime(type)inside a try block. Use separate catch blocks forNullPointerException,ArrayIndexOutOfBoundsException, andIllegalArgumentException. For each, print:Caught specific: [exception class simple name]followed byMessage: [exception message]analyzeWithParent()- CallExceptionThrower.triggerArithmetic()inside a try block. Catch it usingRuntimeException(the parent type). Print:Caught via parent: RuntimeExceptionfollowed byActual type: [exception class simple name]analyzeWithGrandparent()- CallExceptionThrower.triggerGeneric()inside a try block. Catch it usingException(even higher in the hierarchy). Print:Caught via grandparent: Exceptionfollowed byActual type: [exception class simple name]Main.java: Bring your exception analyzer together! You'll receive one input: an exception type string (either"null","index", or"argument").First, print
=== Specific Catch ===and callanalyzeSpecificwith your input.Then print a blank line,
=== Parent Catch ===, and callanalyzeWithParent.Finally, print a blank line,
=== Grandparent Catch ===, and callanalyzeWithGrandparent.
You will receive one input: the exception type to trigger ("null", "index", or "argument").
Use e.getClass().getSimpleName() to get the exception's class name and e.getMessage() to retrieve its message. This challenge shows how catching a parent exception type also catches all its children—a key concept when deciding how specific your exception handling should be!
Cheat sheet
Java's exception handling is built on a class hierarchy rooted in Throwable:
Throwable
├── Error // Serious problems (don't catch)
└── Exception // Recoverable problems
└── RuntimeException // Unchecked exceptionsError represents serious JVM problems like OutOfMemoryError or StackOverflowError that applications shouldn't handle.
Exception splits into checked exceptions (direct subclasses) and unchecked exceptions (subclasses of RuntimeException):
Exception
├── IOException // File/network problems
├── SQLException // Database problems
└── RuntimeException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── IllegalArgumentExceptionCatching a parent exception type also catches all its children:
try {
// some code
} catch (Exception e) {
// Catches ALL exceptions
}
try {
// some code
} catch (RuntimeException e) {
// Catches only runtime exceptions and subclasses
}Use e.getClass().getSimpleName() to get the exception's class name and e.getMessage() to retrieve its message.
Try it yourself
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String type = scanner.nextLine();
// TODO: Print "=== Specific Catch ===" and call ExceptionAnalyzer.analyzeSpecific(type)
// TODO: Print a blank line, then "=== Parent Catch ===", then call ExceptionAnalyzer.analyzeWithParent()
// TODO: Print a blank line, then "=== Grandparent Catch ===", then call ExceptionAnalyzer.analyzeWithGrandparent()
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsFields (Attributes)Constructor MethodConstructor OverloadingRecap - Simple Calculator4Inheritance
Basic Inheritance (extends)The super KeywordMethod Overriding (@Override)Constructor ChainingThe Object ClassSingle & Multilevel InheritWhy No Multi Class InheritRecap - Employee Hierarchy7Special Methods & Object Class
toString() Methodequals() and hashCode()clone() MethodcompareTo() and ComparableComparator InterfaceRecap - Custom Sorting10Exception Handling in OOP
Exception Class HierarchyCustom ExceptionsChecked vs Unchecked ErrorsTry With Resources PatternRecap - Validated User2Access Modifiers & Encapsulate
Access Levels OverviewGetter and Setter MethodsInformation HidingThe final KeywordRecap - Bank Account Manager5Polymorphism
Method Overloading BasicsMethod Overriding (Run-Time)Upcasting and DowncastingThe instanceof OperatorAbstract Classes and MethodsRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceAggregation vs CompositionInner Nested & Anonymous ClassEnums and Enum MethodsRecords (Java 16+)Sealed Classes (Java 17+)3Class Props & Static Member
Instance vs Static VariablesStatic MethodsStatic BlocksConstants (static final)Recap - Counter & Utility6Interfaces & Abstract Classes
Introduction to InterfacesImplementing InterfacesMulti Interface ImplemenDefault & Static in InterfaceAbstract Classes vs InterfacesFunctional InterfacesRecap - Payment System