Java › Exceptions
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?
BeginnerAnswer
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.