Try, Catch, Multi-Catch & Finally Execution Order
1Concept
A `try` block wraps hazardous code. `catch` blocks intercept specific exceptions. Java 7 Multi-Catch (`catch (A | B e)`) consolidates handling without code duplication. The `finally` block ALWAYS executes, even if an exception occurs or a `return` statement is encountered.
2Architecture Diagram
try Block ---> Exception Thrown ---> Matching catch block executes
|
v
finally Block ALWAYS runs ---> Code proceeds safely3Code Example
Core Java
public class TryCatchFinallyDemo {
public static int executeTask(String input) {
try {
System.out.println("1. Inside try block");
return Integer.parseInt(input);
} catch (NumberFormatException | NullPointerException e) {
System.out.println("2. Handled format/null exception: " + e.getClass().getSimpleName());
return -1;
} finally {
System.out.println("3. Finally block ALWAYS executes before method return!");
}
}
public static void main(String[] args) {
int res = executeTask("INVALID_NUMBER");
System.out.println("Final returned result: " + res);
}
}4Expected Output
1. Inside try block 2. Handled format/null exception: NumberFormatException 3. Finally block ALWAYS executes before method return! Final returned result: -1
5Key Takeaways
- ✓Never return a value from a `finally` block; it silently suppresses any return or exception from `try`.
- ✓Multi-catch variables (`e`) are implicitly `final` and cannot be reassigned.
- ✓Exceptions are caught from most specific to most general (subclasses before superclasses).