In the Java 7 release, oracle on exception handling mechanism also made some good changes. These are mainly to improve the catch block and excess throws clause . Let's see how they change.
1. Improved Java catch block 7
In this feature, you can now capture multiple exceptions in a single catch block . Before Java 7, you can only capture only an exception in each catch block.
To specify the desired exception list, use the pipe ( '|') character.
A plurality of Java programs may be captured in a single exception 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 processing more than one type of exception, then the **catch
parameter is implicitfinal
**. In this example,catch
the parameterex
isfinal
, so you can notcatch
assign any value within the block.
2. Java 7 redundancy in the throws clause
This feature saves you use in a method declaration throws clause. See the example below:
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;
}
}
}