What is the basic syntax and control flow of a try-catch-finally block, and what determines which catch block (if multiple exist) handles a thrown exception?
Short answer
A try block contains code that might throw an exception; one or more catch blocks (each specifying a particular exception type) follow, with the JVM checking them in declared order and executing the FIRST catch block whose declared type matches (via instanceof-style checking)…
Advertisement
AModel answer
A try block contains code that might throw an exception; one or more catch blocks (each specifying a particular exception type) follow, with the JVM checking them in declared order and executing the FIRST catch block whose declared type matches (via instanceof-style checking) the actual thrown exception's type -- meaning catch blocks should generally be ordered from most specific to most general (a more general catch block declared before a more specific one would make the specific one unreachable, which the compiler actually flags as an error); an optional finally block always executes afterward regardless of what happened.
try {
riskyOperation();
} catch (FileNotFoundException e) { // more specific, checked first
handleMissingFile(e);
} catch (IOException e) { // more general, only reached if NOT a FileNotFoundException
handleGeneralIOError(e);
} finally {
cleanup();
}Real-world example
A file-processing method with a specific catch (FileNotFoundException e) block preceding a more general catch (IOException e) block correctly routes a missing-file scenario to specialized handling (suggesting the correct file path to the user) while still catching any other I/O failure through the general handler, relying on the JVM's declared-order matching.
Likely follow-ups
- What compiler error occurs if you accidentally place a more general catch block before a more specific one?
- How would you determine the exact runtime type of a caught exception if the catch block declares a general supertype?
Related topics