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 !!

Leave a Reply

7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.