☕ Java Beginner

What is a try-catch block in Java?

Answer

A try-catch block is the fundamental mechanism for handling exceptions in Java. Code that might throw an exception is placed inside the try block. If an exception occurs, execution jumps to the matching catch block that handles that exception type. Multiple catch blocks can follow a single try for different exception types. The optional finally block executes always — whether an exception was thrown or not — and is used for cleanup (closing files, database connections). Since Java 7, a single catch can handle multiple exception types: catch (IOException | SQLException e). Exceptions not caught will propagate up the call stack.