9.2. Multiple Catch Blocks
Multiple catch blocks allow you to handle different types of exceptions differently. This provides granular control over exception handling based on the specific error that occurred.
Syntax for Multiple Catch Blocks
java
try {
// Code that might throw multiple types of exceptions
} catch (FirstExceptionType e1) {
// Handle first type of exception
} catch (SecondExceptionType e2) {
// Handle second type of exception
} catch (ThirdExceptionType e3) {
// Handle third type of exception
}
Order of Catch Blocks
Catch blocks are evaluated in order from top to bottom. More specific exceptions should come before more general ones.
java
try {
// Some operation
} catch (FileNotFoundException e) {
// Specific exception
} catch (IOException e) {
// More general exception
} catch (Exception e) {
// Most general exception
}
Example: File Processing with Multiple Exceptions
java
import java.io.*;
import java.util.Scanner;
public class FileProcessor {
public void readFile(String filename) {
try {
File file = new File(filename);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int number = Integer.parseInt(line);
System.out.println("Number: " + number);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("Error: File '" + filename + "' not found");
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format in file");
} catch (SecurityException e) {
System.out.println("Error: No permission to read file");
}
}
}
Multi-catch Block (Java 7+)
Java 7 introduced the multi-catch block to handle multiple exception types in a single catch block.
java
try {
// Code that might throw similar exceptions
} catch (IOException | SQLException e) {
// Handle both IOException and SQLException
System.out.println("Database or file error: " + e.getMessage());
}
Complete Example: Calculator with Error Handling
java
public class SafeCalculator {
public static void main(String[] args) {
try {
if (args.length < 2) {
throw new IllegalArgumentException("Please provide two numbers");
}
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
if (num2 == 0) {
throw new ArithmeticException("Division by zero");
}
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Please provide command line arguments");
} catch (NumberFormatException e) {
System.out.println("Error: Please provide valid integers");
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Best Practices
- Order matters: Specific exceptions before general ones
- Avoid empty catch blocks: Always handle or log exceptions
- Use multi-catch for related exceptions with similar handling
- Don't catch Throwable: Too broad, includes Errors
java
// Good practice
try {
// risky code
} catch (SpecificException e) {
logger.error("Specific error occurred", e);
} catch (GeneralException e) {
logger.error("General error occurred", e);
}
// Bad practice - too broad
try {
// risky code
} catch (Exception e) {
// too generic
}