January 10, 2024

Java Multi-Catch Exception With Examples

In this post we’ll see a new feature Multi-Catch exception added in Java 7. Using Multi-catch statement, single catch block can handle more than one type of exceptions. You don’t need to write multiple catch blocks to catch different exceptions where exception handling code is similar.

Prior to Multi-Catch exception in Java

If your code throws more than one type of exception, prior to introduction of Multi-Catch exception in Java 7, you would have used multiple catch blocks one per exception.

Let’s say you are reading a file and every line of a file has a single integer. You will read each line of the file as string and then convert that string to int. So you need to handle two exceptions in your code IOException and NumberFormatException.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;

public class MultiCatch {
  private final static Logger logger = Logger.getLogger(MultiCatch.class.getName());
  public static void main(String[] args) throws IOException {
    BufferedReader br = null;
    try{
      String strLine;
      br = new BufferedReader(new InputStreamReader(
                             new FileInputStream(new File("D:\\test.txt"))));
      while((strLine = br.readLine()) != null){
          System.out.println("Line is - " + strLine);
          int num = Integer.parseInt(strLine);
      }
        
    }catch(NumberFormatException  ex){
      logger.info(ex.getMessage());
      throw ex;			
    }catch(IOException ex){
      logger.info(ex.getMessage());
      throw ex;
    }finally{
      try {
        br.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }		
  }
}

Notice some of the problems here-

  1. Even though exception handling code is same, you are logging the exception and then throwing it again, you have to have separate catch blocks.
  2. It is difficult to create a common method to eliminate the duplicated code because the variable ex has different types.
  3. You may even be tempted to write one catch block with Exception as type to catch all the exception rather than writing multiple catch blocks to catch specific exception. But that is not a good practice.

Using Multi-Catch exception in Java

Java 7 onward you can use multi-catch exception to catch multiple exceptions in one catch block. That way you can avoid duplication of code and also the tendency to use Exception class as a catch-all clause which will hide the real cause.

Java multi-catch exception example

Here the same code as used above is written using multi-catch exception

public class MultiCatch {
  private final static Logger logger = Logger.getLogger(MultiCatch.class.getName());
  public static void main(String[] args) throws IOException {
    BufferedReader br = null;
    try{
      String strLine;
      br = new BufferedReader(new InputStreamReader
                      (new FileInputStream
                      (new File("D:\\test.txt"))));
      while((strLine = br.readLine()) != null){
        System.out.println("Line is - " + strLine);
        int num = Integer.parseInt(strLine);
      } 
    }catch(NumberFormatException | IOException  ex){
      logger.info(ex.getMessage());
      throw ex;
    }finally{
      try {
        br.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
Notice the changes here-
  1. Now there is only a single catch block which combines both the catch blocks.
  2. In multi-catch statement you need to separate each exception type in the catch clause using the pipe (|) symbol.

Catch parameter used in multi-catch statement is final

In a multi-catch statement, handling more than one exception type, catch parameter is implicitly final. In the code above, the catch parameter ex is final and therefore you cannot assign any value to it within the catch block.

Byte code generated by multi-catch statement is superior

Bytecode generated by multi-catch statement in Java will be smaller (and thus superior) in comparison to multiple catch blocks that handle only one exception type each. Multi-catch creates no duplication in the bytecode generated by the compiler.

Multi-Catch statement with exception of same type

Trying to catch exceptions of the same type in multi-catch statement will result in compile time error. For example-

catch (FileNotFoundException | IOException ex) {
  Logger.error(ex);
}

This multi-catch results in compile time error as FileNotFoundException is the child class of IOException. You will get the error as- The exception FileNotFoundException is already caught by the alternative IOException.

Reference- https://docs.oracle.com/javase/8/docs/technotes/guides/language/catch-multiple.html

That's all for the topic Java Multi-Catch Exception With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment