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

后端 未结 3 1014
梦毁少年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:45

    In both instance, the code with throw a java.lang.ArithmeticException, however the return in the finally discards the exception and instead the method exits without forwarding the exception to the caller.

    This is one of the reason why in general you should not use a return in a finally-block.

    This is described in the Java Language Specification (8), 14.20.2 Execution of try-finally and try-catch-finally:

    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

    ... (some similar but for this case irrelevant rules left out)

    • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the finally block is executed. Then there is a choice:

      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.

      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).

    You can find the definition of abrupt and normal completion in JLS 14.1 Normal and Abrupt Completion of Statements. But basically a return is considered an abrupt completion.

提交回复
热议问题