Multiple catch blocks let you handle different errors separately in your program. This helps fix problems more clearly and safely.
0
0
Multiple catch blocks in Java
Introduction
When your code might cause different types of errors and you want to respond to each one differently.
When reading a file that might not exist or might have wrong data format.
When working with user input that could cause different problems like wrong number or text.
When calling methods that throw different exceptions and you want to handle each case.
Syntax
Java
try { // code that might throw exceptions } catch (ExceptionType1 e1) { // handle ExceptionType1 } catch (ExceptionType2 e2) { // handle ExceptionType2 } // more catch blocks as needed
Each catch block handles one specific type of exception.
Catch blocks are checked in order; the first matching one runs.
Examples
This example catches a specific array error first, then any other error.
Java
try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index is out of range."); } catch (Exception e) { System.out.println("Some other error happened."); }
This example handles division by zero separately from other errors.
Java
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); } catch (Exception e) { System.out.println("General error."); }
Sample Program
The program tries to access an invalid array index, which causes an exception. The first catch block matches and runs, so the arithmetic error is not reached.
Java
public class MultipleCatchExample { public static void main(String[] args) { try { int[] arr = {1, 2, 3}; System.out.println(arr[3]); // This will cause ArrayIndexOutOfBoundsException int result = 10 / 0; // This will cause ArithmeticException but won't run because of previous error } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Caught an array index error."); } catch (ArithmeticException e) { System.out.println("Caught an arithmetic error."); } catch (Exception e) { System.out.println("Caught some other error."); } } }
OutputSuccess
Important Notes
Put more specific exceptions before general ones like Exception.
Only one catch block runs per try.
Use multiple catch blocks to give clear messages or recovery steps for different errors.
Summary
Multiple catch blocks let you handle different errors separately.
They run in order, and only the first matching one runs.
Always put specific exceptions before general ones.