Matching Exceptions to catch Clauses
What you'll learn: How the JVM decides which catch block handles a thrown exception based on type compatibility and inheritance.
When an exception is thrown inside a try block, the JVM doesn't randomly pick a catch clause to handle it. Instead, it performs a careful matching process using the exception's type and Java's inheritance hierarchy.
How the Matching Process Works
The JVM examines catch blocks in the order they appear from top to bottom. For each catch clause, it checks: "Is the thrown exception an instance of this catch block's declared type?" This uses the same "is-a" relationship you know from inheritance.
If the thrown exception's class matches (either exactly or through inheritance), that catch block executes and the search stops. If no match is found, the exception propagates up the call stack.
Type Compatibility Through Inheritance
Remember that every exception class extends from Throwable. If you throw a FileNotFoundException, it's also an IOException (its parent class) and also an Exception (its grandparent). A catch block declared for any of these types would match.
Analogy: Think of it like sorting mail into bins labeled by category. If you have bins labeled "Bills," "Bank Mail," and "All Mail," a bank bill would match all three—but you'd drop it in the first matching bin you encounter.
Order Matters
Because matching stops at the first compatible type, you must place more specific exception types before more general ones. A catch (Exception e) would match nearly everything, so it should come last.
Key Takeaway: The JVM matches thrown exceptions to catch blocks using type compatibility and inheritance, checking clauses in order from top to bottom and executing the first match it finds.