Java – Throwing same exception inside catch block

exceptionexception handlingjavatry-catch

I have following 2 code snippets and I am wondering what makes java compiler (In Eclipse with Java 7) to show error for 2nd snippet and why not for 1st one.

Here are the code snippets:

snippet 1

public class TestTryCatch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(get());
    }

    public static int get(){
        try{
            System.out.println("In try...");
            throw new Exception("SampleException");
        }catch(Exception e){
            System.out.println("In catch...");
            throw new Exception("NewException");
        }
        finally{
            System.out.println("In finally...");
            return 2;
        }
    }
}

snippet 2

public class TestTryCatch {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(get());
    }

    public static int get(){
        try{
            System.out.println("In try...");
            throw new Exception("SampleException");
        }catch(Exception e){
            System.out.println("In catch...");
            throw new Exception("NewException");
        }
//      finally{
//          System.out.println("In finally...");
//          return 2;
//      }
    }
}

In eclipse, snippet1 shows to add 'SuppressWarning' for finally block, but in snippet2, it shows to add 'throws or try-catch' block for the throw statement in catch block.

I had a detailed look at following questions, but they didn't provide any concrete reason for this.

Best Answer

The finally block should always execute. This is the main reason. The exception is thrown in the catch block but return statement executed in the finally block masks exception. Either remove finally block or move return statement out of the finally block.