0

I know that the value returned from final block always overwrite whatever is returned, but is it supposed to overwrite or suppress a thrown exception?

public static String callme() throws Exception {
    try {
        throw new Exception();
    } catch (Exception e) {
        System.out.println("inside the catch block");
        throw e;
    } finally {
        System.out.println("Inside finally");
        return "returned from finally";
    }

}

public static void main(String[] args) {
    try {
        System.out.println(callme());
    } catch (Exception e) {
        System.out.println("something is caught");
    }
}

expected output -

inside the catch block
Inside finally
returned from finally
something is caught

reality -

inside the catch block
Inside finally
returned from finally

I wanna ask

  1. why this is happening?

  2. if its happening then isn't it bad, because the calling method won't know the exception thrown

azro
  • 53,056
  • 7
  • 34
  • 70
Piyush Kumar
  • 191
  • 1
  • 10
  • https://stackoverflow.com/questions/3779285/exception-thrown-in-catch-and-finally-clause – Jan Gassen Mar 18 '20 at 15:57
  • 1
    This is happening because you put a return statement inside your finally. "A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded." See: [Can we use “return” in finally block](https://stackoverflow.com/questions/18205493/can-we-use-return-in-finally-block) Returning something from a finally block is rarely a good diea or usefull. – OH GOD SPIDERS Mar 18 '20 at 15:58
  • You should never call return in a finally block. This is never good coding. If you understand that, you won't have to worry about how any of this works – ControlAltDel Mar 18 '20 at 16:02

0 Answers0