Try Catch in Java
The try-catch block is Java's fundamental syntax for handling exceptions. Code that might throw an exception goes inside the try block. One or more catch b...
Catching and Responding to Exceptions
The try-catch block is Java's fundamental syntax for handling exceptions. Code that might throw an exception goes inside the try block. One or more catch blocks follow, each specifying the exception type it handles. If an exception occurs in the try block, Java immediately stops executing the remaining try code, looks for a catch block whose type matches the exception, and transfers control there. If no matching catch block exists, the exception propagates to the caller.
Multiple Catch Blocks A single try block can have multiple catch clauses, each handling a different exception type. Java searches catch blocks from top to bottom and uses the first matching one. Because of inheritance, more specific types must appear before more general types. If you place catch(Exception e) before catch(IOException e), the compiler reports a compile error because the broader type always matches first, making the specific clause unreachable.
Multi-Catch Syntax (Java 7+) Java 7 introduced the multi-catch syntax that handles multiple unrelated exception types in a single catch block: catch (IOException | ParseException e). This is cleaner than duplicating the same handler for each type. The caught variable e is implicitly final in a multi-catch clause—you cannot reassign it inside the block. This limitation exists because assigning a subtype of one of the listed exceptions would create ambiguity about the type.
Try-With-Resources Java 7 also introduced try-with-resources, which automatically closes any resource declared in the try's parentheses when the block exits—whether normally or due to an exception. A resource must implement java.lang.AutoCloseable. This eliminates the boilerplate of calling close() in a finally block and handles the tricky case where both the try body and the close() call throw exceptions (the close exception is suppressed and attached to the primary exception).
Code Example: // Multi-catch and try-with-resources combined try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (FileNotFoundException e) { System.err.println("File not found: " + e.getMessage()); } catch (IOException e) { System.err.println("Read error: " + e.getMessage()); } // br is automatically closed here
Interview Tip: Interviewers ask what happens to the return value if a try block has a return statement and a finally block also has a return statement. The finally block's return overrides the try block's return, which is almost always unintended and considered a serious bug. The practical rule is to never place a return statement inside a finally block. Knowing this corner case demonstrates careful study of Java's exception mechanics.