The secrets of Java multiple catch exceptions

Need of Java multiple catch exceptions

A try block can follow multiple catch blocks which means we can do Java multiple catch exceptions. We handle different exceptions in different ways. Lets check our previous example of opening a file.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = null;

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try(BufferedReader br = new BufferedReader(new FileReader("sample.txt"));) {
      System.out.println(br.readLine());
      list.add(br.readLine());
    } catch (Exception e) {
      System.out.println("Something went wrong...");
      e.printStackTrace();
    }
  }
}

Here the output will be same if the file is not present on that location and if any null pointer exception comes. But what if we want to improve the user experience we want to show an error message like “File not found at specified location” in case of file is not available on that location and we want to show an error message as “NullPointerException Occurred. Please check your code and try again” in case of any NPE and a generic message as “Something went wrong…” in case of any other exception.

Lets edit our code and 2 more catch blocks for IOException to handle all file related exceptions and NullPointerException to handle all NPEs.

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

public class TryCatchFinallyExample {

  static List<String> list = null;

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try(BufferedReader br = new BufferedReader(new FileReader("sample.txt"));) {
      System.out.println(br.readLine());
      list.add(br.readLine());
    } catch (IOException e) {
      System.out.println("File not found at specified location");
      e.printStackTrace();
    } catch (NullPointerException e) {
      System.out.println(e.getMessage() + " Occurred. Please check your code and try again");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("Something went wrong...");
      e.printStackTrace();
    }
  }
}

Now if we run our program then it will behave differently as below

  1. If the file is not available on the location then it will output as
Reading a sample file
File not found at specified location
java.io.FileNotFoundException: samples.txt (No such file or directory)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.io.FileInputStream.<init>(FileInputStream.java:93)
	at java.io.FileReader.<init>(FileReader.java:58)
	at com.onlyfullstack.TryCatchFinallyExample.main(TryCatchFinallyExample.java:14)

Process finished with exit code 0

2. If any NullPointerException occurs

Reading a sample file
Learn Exception handling
null Occurred. Please check your code and try again
java.lang.NullPointerException
	at com.onlyfullstack.TryCatchFinallyExample.main(TryCatchFinallyExample.java:16)

Process finished with exit code 0

3. and in case of any other exception

Reading a sample file
Learn Exception handling
Something went wrong...
java.lang.ArithmeticException: / by zero
	at com.onlyfullstack.TryCatchFinallyExample.main(TryCatchFinallyExample.java:18)

Process finished with exit code 0

Alright. now we are handling all the exceptions differently. thats great.

But wait… Let me share 1 more advance technique of handling an exception which is called as “Improved catch block in Java 7” which was introduced in Java 7. Java multiple catch exceptions

Java multiple catch exceptions

Lets go back to our example and add int i = 5/0; line to it. As we know, java will throw ArithmeticException whenever we try to divide any number by zero. Now we will catch this exception and will put the message as “/ by zero Occurred. Please check your code and try again”

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = new ArrayList<>();

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try(BufferedReader br = new BufferedReader(new FileReader("sample.txt"));) {
      System.out.println(br.readLine());
      list.add(br.readLine());
      int i = 5/0;
    } catch (IOException e) {
      System.out.println("File not found at specified location");
      e.printStackTrace();
    } catch (NullPointerException e) {
      System.out.println(e.getMessage() + " Occurred. Please check your code and try again");
      e.printStackTrace();
    } catch (ArithmeticException e) {
      System.out.println(e.getMessage() + " Occurred. Please check your code and try again");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("Something went wrong...");
      e.printStackTrace();
    }
  }
}

Output of above program is

Reading a sample file
Learn Exception handling
/ by zero Occurred. Please check your code and try again
java.lang.ArithmeticException: / by zero
	at com.onlyfullsttack.TryCatchFinallyExample.main(TryCatchFinallyExample.java:18)

Process finished with exit code 0

Improved catch block in Java 7


Wait. the handling of NullPointerException and ArithmeticException is same. Isn’t it? so this is a redundant code right? so to overcome this problem Java 7 has introduced an improved catch block in java where we can provide multiple exception types in same catch block with the help of pipe.

So now instead of having 2 catch blocks for NullPointerException and ArithmeticException we will have combine them into one catch block as below.

} catch (NullPointerException | ArithmeticException e) {
   System.out.println(e.getMessage() + " Occurred. Please check your code and try again");
   e.printStackTrace();
} 

Easy and less duplication 😊.

Here the complete code –

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class TryCatchFinallyExample {

  static List<String> list = new ArrayList<>();

  public static void main(String[] args) {
    System.out.println("Reading a sample file");
    try(BufferedReader br = new BufferedReader(new FileReader("sample.txt"));) {
      System.out.println(br.readLine());
      list.add(br.readLine());
      int i = 5/0;
    } catch (IOException e) {
      System.out.println("File not found at specified location");
      e.printStackTrace();
    } catch (NullPointerException | ArithmeticException e) {
      System.out.println(e.getMessage() + " Occured. Please check your code and try again");
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("Something went wrong...");
      e.printStackTrace();
    }
  }
}

Thats how we have used improved catch block feature of Java 7 to remove the duplicate code.

Guys if you like this article then please share it on social media.