In what order should catch blocks be written, and what is multi-catch in Java?
Catch blocks are checked top to bottom, so subclasses must come before their parents or the code will not compile. Multi-catch uses a pipe to handle several unrelated exceptions in one block.
Explain it simply
At a hospital reception you first ask "is it a heart emergency?" and only then "is it any emergency?". If the general question came first, the specific one would never get asked. Java prevents that mistake at compile time.
Example
try {
Object o = "text";
Integer n = (Integer) o; // ClassCastException
} catch (ClassCastException | NumberFormatException e) { // multi-catch
System.out.println("bad data: " + e.getClass().getSimpleName());
} catch (RuntimeException e) { // general case after specific
System.out.println("other runtime problem");
}
// prints: bad data: ClassCastException
// catch (RuntimeException e) { }
// catch (ClassCastException e) { } // compile error: already caughtWhat to say in the interview
"The first matching catch block runs, so specific exceptions go first and general ones last. A catch for a subclass placed after its parent is a compile error because it is unreachable. Multi-catch with the pipe operator, from Java 7, removes duplicated handling code, but the listed types cannot be related by inheritance, and the variable is implicitly final."
Common mistakes
- Listing
Exception | IOExceptionin one multi-catch. Types related by inheritance are rejected.