Java Catch Multiple Exceptions

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn java catch multiple exceptions.

java catch multiple exceptions

Java catch multiple exceptions

A java program can have ‘n’ number of catch blocks with single try blocks but it is important to know that the order of catch block.

Also Read – Java Rename File

Catch block has been upgraded in java 7 to handle multiple exceptions in a single try catch block. Now let’s understand java try catch multiple exceptions with an example,

public class JavaCatchMultiple 
{
   public static void main(String[] args) 
   {
      try
      { 
         int num[] = new int[5]; 
         num[5] = 30 / 0; 
      } 
      catch(ArithmeticException ae)
      {
         System.out.println("First catch");
      } 
      catch(ArrayIndexOutOfBoundsException aioe)
      {
         System.out.println("Second catch");
      } 
      catch(Exception e)
      {
         System.out.println("Default catch!!");
      } 
      System.out.println("Remaining code..."); 
   }
}

Output :

First catch
Remaining code…

We use multiple catch block when a java program execute various tasks at the instance of different exceptions.

NOTE :

  • Try block can have multiple catch block.
  • A single try block can have ‘n’ number of catch blocks.
  • If an exception occur, exception is passed to first catch block. If the exception matches in the first catch block it gets caught, if not the exception is moved to next catch block. This will continue until the exception is caught.
  • Use multiple catch blocks for catching multiple exceptions and having similar code. Hence reducing code duplication.
  • At a time only one catch block is executed.
  • At a time only one exception is occurred.

To catch multiple exceptions in java (before) we would catch exceptions one by one like this,

catch(IOException ex)
{
   logger.error(ex);
   throw new MyException(ex.getMessage());
catch(SQLException ex)
{
   logger.error(ex);
   throw new MyException(ex.getMessage());
}

But now in Java 7 we can catch multiple exceptions in a single catch block using pipe symbol (|) like this,

catch(IOException | SQLException ex)
{
   logger.error(ex);
   throw new MyException(ex.getMessage());
}

Here parameter “ex” is constant and can’t change it. This feature generates bytecode which is smaller and hence reduces code redundancy.


Java rethrow exception

Here we are going to learn rethrow exception java. Let’s see an example first,

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class JavaRethrow 
{
   public static void main(String[] args) 
   {
      try
      {
         new JavaRethrow().getInfoFile();
      }
      catch(IOException ioe)
      {
         System.out.println("Here Exception is handled!!");
      }
      System.out.println("Default.....");
   }

   private void getInfoFile() throws IOException
   {
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter filename : ");
      String strName = sc.nextLine();
      sc.close();

      BufferedReader br;
      try
      {
         br = new BufferedReader(new FileReader(strName));
         String str = null;

         while((str = br.readLine()) != null) // reading line one at a time, returns null when nothing to read
         {
            System.out.println(str);
         }
         br.close();
      }
      catch(IOException ioe)
      {
         System.out.println("Rethrow IOException");
         throw ioe; // here we are rethrowing same exception in catch block 
      }
   }
}

Output :

Please enter filename : win.txt
Rethrow IOException
Here Exception is handled!!
Default…..

In the above example I have declared the class JavaRethrow. It has main method. From this method I’m calling getInfoFile() method.

In getInfoFile() method we are using BufferedReader to read the file content and displaying the file content.

If any IOException occurs we are rethrowing the exception. This rethrown exception is handled in “main” method catch block.


conclusion

That’s all for now. In this post we learnt catch multiple exceptions in java and rethrow exception with an example.

I hope you guys have understood the concept of multiple catch blocks in java. You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Related Posts