Different syntaxes to write try-catch blocks in Java
In Java, the try-catch block has multiple variations and syntaxes to handle exceptions. Here are the different ways you can write a try-catch block:
1. Basic try-catch Block
Handles a single exception type.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
try {
int result = 10 / 0; // May throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
2. Multiple catch Blocks
Handles multiple specific exception types.
try {
// Code that may throw exceptions
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
}
Example:
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // May throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic error.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
3. Using catch Block for Multiple Exception Types (Java 7+)
Handles multiple exception types in a single catch block using the pipe (|) operator.
try {
// Code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 e) {
// Code to handle either ExceptionType1 or ExceptionType2
}
Example:
try {
int result = 10 / 0;
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
4. try-catch-finally Block
Adds a finally block to execute cleanup code regardless of whether an exception occurs or not.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This block always executes.");
}
5. try-finally Block
If no catch block is needed, a finally block can be used alone for cleanup.
try {
// Code that may throw an exception
} finally {
// Code that will always execute
}
Example:
try {
int result = 10 / 0;
} finally {
System.out.println("This block always executes.");
}
6. Nested try-catch Blocks
A try-catch block inside another try or catch block.
try {
try {
// Nested try block
} catch (ExceptionType e) {
// Handle exception from nested try block
}
} catch (ExceptionType e) {
// Handle exception from outer try block
}
Example:
try {
try {
int result = 10 / 0; // Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch: Cannot divide by zero.");
}
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Outer catch: Array index out of bounds.");
}
7. try-with-resources (Java 7+)
Automatically closes resources (like files or database connections) when the try block completes.
try (ResourceType resource = new ResourceType()) {
// Code that uses the resource
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
String line = reader.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
8. try-catch with Custom Exception
Catch user-defined (custom) exceptions.
try {
// Code that may throw a custom exception
} catch (CustomException e) {
// Handle the custom exception
}
Example:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
try {
throw new CustomException("Custom exception occurred!");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
Summary:
Java offers flexible ways to write try-catch blocks:
Each variation serves specific use cases to make exception handling more efficient and readable.