We have already learnt about the try catch statements in java. Try-Catch statement is used to handle exceptions in java.
Multiple Catch Blocks : Catching Multiple Exceptions
public class ExceptionExample { public static void main(String argv[]) { int num1 = 10; int num2 = 0; int result = 0; int arr[] = new int[5]; try { arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3; arr[4] = 4; arr[5] = 5; result = num1 / num2; System.out.println("Result of Division : " + result); }catch (ArithmeticException e) { System.out.println("Err: Divided by Zero"); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Err: Array Out of Bound"); } } }
Output :
Err: Array Out of Bound
In the above example we have two lines that might throw an exception i.e
arr[5] = 5;
above statement can cause array index out of bound exception and
result = num1 / num2;
this can cause arithmetic exception. To Handle these two different types of exception we have included two catch blocks for single try block.
}catch (ArithmeticException e) { System.out.println("Err: Divided by Zero"); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Err: Array Out of Bound"); }
Now Inside the try block when exception is thrown then type of the exception thrown is compared with the type of exception of each catch block.
If type of exception thrown is matched with the type of exception from catch then it will execute corresponding catch block.
Notes :
- At a time only single catch block can be executed. After the execution of catch block control goes to the statement next to the try block.
- At a time Only single exception can be handled.
- All the exceptions or catch blocks must be arranged in order. [Refer the Exception Hierarchy]
Catch Block must be arranged from Most Specific to Most General :
If we wrote catch block like this -
}catch (Exception e) { System.out.println("Err: Exception Occurred"); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Err: Array Out of Bound"); }
- All the exceptions will be catched in the First Catch block because Exception is superclass of all the exceptions.
- In the above program ArrayIndexOutOfBoundsException is an subclass of Exception Class.
Writing above code will throw following error message after compiling it -
The post Multiple Catch Blocks : Exception Handling in Java appeared first on Learn Java Programming.