Returning from a finally block in Java

前端 未结 6 1924
醉梦人生
醉梦人生 2020-11-22 11:02

I was surprised recently to find that it\'s possible to have a return statement in a finally block in Java.

It seems like lots of people think it\'s a bad thing to d

6条回答
  •  既然无缘
    2020-11-22 12:01

    Returning from inside a finally block will cause exceptions to be lost.

    A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.

    According to the Java Language Specification:

    If execution of the try block completes abruptly for any other reason R, then the finally block is executed, and then there is a choice:

       If the finally block completes normally, then the try statement
       completes  abruptly for reason R.
    
       If the finally block completes abruptly for reason S, then the try
       statement  completes abruptly for reason S (and reason R is
       discarded).
    

    Note: As per JLS 14.17 - a return statement always completes abruptly.

提交回复
热议问题