try/finally without catch and return value

This question already has an answer here:

  • Does finally always execute in Java? 50 answers

  • From the JLS (emphasis mine):

    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    [...]
    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 ).

  • TL/DR
    This means if you return within the finally block, the method returns without throwing an exception.
    /TL/DR

    Besides return , there are other statementes that can cause the finally block to complete abruptly and forget about the exception. They are defined in the JLS Section 14.1. Basically, it is break , continue , return or an exception (either thrown or caused by a statement/method). The complete try/catch/finally block then completes with this reason.

    There are a few more cases ín the specification of try/catch/finally , especially if there is no exception or a matching catch clause exists. It comes down to finally beats catch beats try .


    When your exception is thrown, it will first go through your finally block.

    If your finally block does not return or throw anything then the original exception is passed on.

    If your finally block on the other hand returns a value, then the exception is no longer propagated at all.

  • Reference: JLS about try-finally

  • Look at the execution of try catch finally.

    From java language specification -jls-14.20.2

    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 ).

    链接地址: http://www.djcxy.com/p/73694.html

    上一篇: java:尝试最后阻止执行

    下一篇: 尝试/最后没有捕获和返回值