Core JAVA

Multiple catch block Handling

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.
 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.

  1. Rule: At a time only one Exception is occurred and at a time only one catch block is executed.
  2. 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

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

2 years ago