A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following
try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }
The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.
public class MultiCatchBlock { public static void main (String args[]) { int array[] = {20,10,30}; int num1 = 15,num2 = 0; int res = 0; try { res = num1/num2; System.out.println("The result is" +res); for(int ct =2;ct >=0; ct--) { System.out.println("The value of array are" +array[ct]); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error?. Array is out of Bounds"); } catch (ArithmeticException e) { System.out.println ("Can't be divided by Zero"); } } }
Output of the program:
In this example we have used two catch clause catching the exception ArrayIndexOutOfBoundsException and ArithmeticException in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time the first catch block is skipped and the second catch block handles the error.
- Rule: At a time only one Exception is occurred and at a time only one catch block is executed.
- Rule: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .
public class MultiCatchBlock { public static void main (String args[]) { int array[] = {20,10,30}; int num1 = 15,num2 = 0; int res = 0; try { res = num1/num2; System.out.println("The result is" +res); for(int ct =2;ct >=0; ct--) { System.out.println("The value of array are" +array[ct]); } } catch (Exception e) { System.out.println("Common Exception completed"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Error?. Array is out of Bounds"); } catch (ArithmeticException e) { System.out.println ("Can't be divided by Zero"); } } }
Output:
Compile-time error