java7 exception handling enhancements

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 catchblock processing more than one type of exception, then the ** catchparameter is implicit final**. In this example, catchthe parameter exis final, so you can not catchassign 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;
        }
    }
}

Guess you like

Origin www.cnblogs.com/qingmiaokeji/p/12555359.html