top of page

Multiple Catch block in java

  • Writer: Keshari Abeysinghe
    Keshari Abeysinghe
  • Feb 27, 2020
  • 1 min read

A try block can be followed by multiple catch blocks.lets see few rules about multiple catch blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.


1. A single try block can have any number of catch blocks.


2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see the examples of NullPointerException and ArrayIndexOutOfBoundsException, refer this article: Exception Handling example programs.


3. If no exception occurs in try block then the catch blocks are completely ignored.


4. Corresponding catch blocks execute for that specific type of exception:

catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException

catch(NullPointerException e) is a catch block that can handle NullPointerException


5. It is able to throw exception, which is an advanced topic and I have covered it in separate tutorials: user defined exception, throws keyword, throw vs throws.


Example

class Example1
{ 
  public static void main(String args[]){
  try{
  int a[]=new int[7];
  a[4]=30/0;
  System.out.println("First print statement in try block");
  }
  catch(ArithmeticException e){
  System.out.println("Warning: ArithmeticException");
  
  catch(ArrayIndexOutOfBoundsException e){
  System.out.println("Warning: ArrayIndexOutOfBoundsException");
  }
  catch(Exception e){
  System.out.println("Warning: Some Other exception");
  }
  System.out.println("Out of try-catch block...");
  }
}

Excepted Output


WarningArithmeticException
Out of try-catch block...

Lets see upcoming articles with more about on exception handling.

Happy Coding!

Recent Posts

See All
Try -Catch in Java

Try block The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which...

 
 
 
Nested Try-Catch block

When a try catch block is present in another try block then it is called the nested try catch block.Sometimes a situation may arise where...

 
 
 

Comments


Subscribe Form

Thanks for submitting!

©2020 by Quick Code. Proudly created with Wix.com

bottom of page