Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing same exception inside catch block

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.

  • exception-thrown-inside-catch-block-will-it-be-caught-again
  • re-throw-an-exception-inside-catch-block
  • throwing-an-exception-in-catch-block
like image 813
ms_27 Avatar asked Oct 15 '25 10:10

ms_27


2 Answers

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.

The 2nd snippet does not have a return value. It has been commented out with the finally clause.

Try this

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");
    }
    return 2;   // must return a value
//      finally{
//          System.out.println("In finally...");
//          return 2;
//      }
like image 30
Mike Murphy Avatar answered Oct 16 '25 23:10

Mike Murphy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!