try and Finally giving exception with no return statement , but there is no exception when return statement is written in method

后端 未结 3 1020
梦毁少年i
梦毁少年i 2021-01-29 12:16

Please explain why Exception comes in first program but not in second program.

1) without return statement in read method

class Example
{   
    public s         


        
3条回答
  •  半阙折子戏
    2021-01-29 12:41

    The reason is given in the Java Language Specification rules governing the execution of try/finally blocks. Essentially

    • if the try block throws an exception E and the finally completes normally then the overall try/finally throws E
    • if the try block throws E but the finally does not complete normally, then E is ignored and the overall try/finally "completes abruptly" for the reason arising from the finally block

    An explicit return is considered abrupt rather than normal completion, so in your example 2 the return inside the finally masks the divide-by-zero exception raised by the try.

提交回复
热议问题