Java 7: Catching multiple exceptions

  Java Features     Java 5     Java 7     Java 8  
Java 7 features
 Binary literals |   Strings in switch statements |   Catching multiple exceptions |   Try with resources |   Type inference |   Underscores in numeric literals |   By date 

In the following example we apply catching multiple exception types, which is a new feature in JSE7, In the earlier Java versions you could catch each exception type in a separate block, but in Java 7 you can catch multiple types of exceptions in one block. For more info click here to read Oracle’s explanation.

Example 1: Catching two exception types

What is the output of the following code?

public class HandlingMultiException
{
  public static void main(String args[])
  {
    try
    {
      String[] arrCountries = new String[7];
      arrCountries[6].substring(3);
    }
    // catching two exception types in one block
    catch(NullPointerException | ArrayIndexOutOfBoundsException e)
    {
      System.out.println(e.getMessage());
    }
  }
}
Author: Sar Maroof

Answer explanation

  1. In the previous code we created an array with length of 7. If you try to access an element of the array greater than its length, that would result in ArrayIndexOutOfBoundsException. For example arrCountries[8].substring(3); would result in ArrayIndexOutOfBoundsException.
  2. If you try to access a substring of any of the elements, that would result in NullPointerException. That is because the elements of the array are not initialized.
    The statement arrCountries[6].substring(3); results in NullPointerException.

The correct answer is: null.

In the earlier Java versions we used more lines of code to write the same program. Here below how the previous code looks like in older Java versions.

public class HandlingException
{
  public static void main(String args[])
  {
    try
    {
      String[] arrCountries = new String[7];
      arrCountries[6].substring(3);
    }
    catch(NullPointerException e)
    {
      System.out.println(e.getMessage());
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println(e.getMessage());
    }
  }
}

 





Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *