Java try, catch, finally – Complete Guide with Examples
Learn Java try, catch, and finally blocks to handle exceptions gracefully, ensure cleanup with finally, and write robust and error-free Java programs.
try, catch, and finally in Java – Complete Detailed Tutorial
Java provides a mechanism to handle runtime exceptions using try, catch, and finally blocks.
This ensures that program execution continues even when an error occurs.
1. try Block
- Contains code that might throw an exception
- Must be followed by at least one catch or finally block
Syntax:
Example:
2. catch Block
- Handles the exception thrown in try block
- Takes an exception parameter
- Can have multiple catch blocks for different exception types
Syntax:
Example:
3. finally Block
- Always executes whether an exception occurs or not
- Used for cleanup operations (like closing files, releasing resources)
- Optional, but recommended when using resources
Syntax:
Example:
Output:
4. Multiple catch Blocks
- Catch different types of exceptions separately
- Useful for specific handling
Output:
5. try-with-resources (Java 7+)
- Automatically closes resources like files or streams
- Implements AutoCloseable interface
Example:
- No need to explicitly close the
BufferedReader
6. Key Points
- try block: risky code
- catch block: handle exceptions
- finally block: executes always, used for cleanup
- Multiple catch: handle different exception types
- try-with-resources: automatically closes resources