Java 7 – Exception handling enhancements

With release of Java 7, oracle has done some good changes in exception handling mechanism also. Primarily these are improved catch block and redundant throws clause. Lets see how they got changed.

1. Improved catch block in Java 7

In this feature, now you can catch multiple exceptions in single catch block. Before Java 7, you was restricted to catch only one exception per catch block.

To specify the list of expected exceptions a pipe (‘|’) character is used.

Java program to catch multiple exceptions in single catch block.

try
{
    //Do some processing which throws NullPointerException;
    throw new NullPointerException();
}
//You can catch multiple exception added after 'pipe' character
catch( NullPointerException npe | IndexOutOfBoundsException iobe )
{
       throw ex;
}

If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

2. Redundant throws clause in Java 7

This feature liberate you from using throws clause in method declaration. See in below given example:

public class MultipleExceptionsInCatchBlock {

	public static void main(String[] args)
	{
			sampleMethod();
	}

	public static void sampleMethod()
					//throws Throwable	//No need to do this
	{
		try
		{
			//Do some processing which throws NullPointerException; I am sending directly
			throw new NullPointerException();
		}
		//You can catch multiple exception added after 'pipe' character
		catch(NullPointerException | IndexOutOfBoundsException ex)
		{
			throw ex;
		}
		//Now method sampleMethod() do not need to have 'throws' clause
		catch(Throwable ex)
		{
			throw ex;
		}
	}
}

Java runtime is intelligent enough to identify the exact exception class in caller method.

If you compile above code with Java 6 or earlier release, It will give compilation error and will ask you do to declare throws clause.

In my opinion, first improvement is definitely a good addition for Java developers. But, I really do not see the second addition so much relevant. Again, its my view.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

7 thoughts on “Java 7 – Exception handling enhancements”

  1. Even if you do

     
    catch(ArithmeticException | ArrayIndexOutOfBoundsException | Exception ex){
          ex.printStackTrace();
    }
    

    Then also you will encounter compilation issues. Saying the exception ArithmeticException is already caught by alternative exception. something like this

    Reply
  2. Anshudeep,

      
    catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
    ex.printStackTrace();
    }   
    
    gives you CE not because of the order from left to right. It is because of Exception is parent class for Class ArrayIndexOutOfBoundsException
    
    java.lang.Object
    java.lang.Throwable
    java.lang.Exception
    java.lang.RuntimeException
    java.lang.IndexOutOfBoundsException
    java.lang.ArrayIndexOutOfBoundsException
    
    even for NullpointerException the same case it is fall under Exception class only.
    
    java.lang.Object
    java.lang.Throwable
    java.lang.Exception
    java.lang.RuntimeException
    java.lang.NullPointerException
    All Implemented Interfaces:
    

    So, If you wanted to catch same sublevel exceptions JAVA people made to throw a super/Generic exception instead of individual at same level.

    Please do let me know if you found something wrong here..

    Reply
  3. To Add one more point –
    While joining multiple statement using | make sure that you go from subtype exception class to parent exception classes. Doing something like this will result in compiler error.

    // This will give compiler error
    catch(Exception | ArithmeticException | ArrayIndexOutOfBoundsException ex){
    ex.printStackTrace();
    }

    Reply
  4. Suppose as in your above example if I want to know print the stacktrace of Null pointer exception and Index Out of bound exception, how I will print with the help of one parameter “ex”.

    eg:-

    prior to java 7
    try{}
    catch(NullPointer Exception np){
    np.printstackTrace();
    }
    catch(Index outof bound Exception op){
    op.printstackTrace();
    }

    In this code I have a clear idea which exception class it is going, but in java 7 in single catch statement how I will know because of what my exception is coming ?

    Reply
    • Subrat, in above case in you code, you can use instanceof if such information is needed. It will solve the problem.

      Actually, i think confusion arises here because of my choice of exception classes which are way different in nature. So, let correct the example:

      try
      {
      //validating user mail
      }
      catch(NullPointerException | InvalidFormatException ex)
      {
      //Build invalid email response and return to calling code or user
      }

      There can be so many such scenarios where exception types just don’t matter and all are treated as same.

      Anyways, it is just another feature in java 7 worth knowing, and nobody is forced to use it. I hope, I make sense.

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.