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:
try {
// code that may throw exception
}
Example:
try {
int result = 10 / 0; // ArithmeticException
}
2. catch Block
- Handles the exception thrown in try block
- Takes an exception parameter
- Can have multiple catch blocks for different exception types
Syntax:
catch (ExceptionType e) {
// handle exception
}
Example:
try {
int result = 10 / 0; // may throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}
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:
finally {
// cleanup code
}
Example:
public class Main {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of range: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}
Output:
Index out of range: 5
This block always executes
4. Multiple catch Blocks
- Catch different types of exceptions separately
- Useful for specific handling
public class Main {
public static void main(String[] args) {
try {
int a = 10 / 0; // ArithmeticException
int[] arr = {1, 2};
System.out.println(arr[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is invalid");
} finally {
System.out.println("Program executed finally block");
}
}
}
Output:
Cannot divide by zero
Program executed finally block
5. try-with-resources (Java 7+)
- Automatically closes resources like files or streams
- Implements AutoCloseable interface
Example:
import java.io.*;
public class Main {
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("File error: " + e.getMessage());
}
}
}
- 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