Does a finally block always get executed in Java?

前端 未结 30 1597
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 07:35

    Answer is simple YES.

    INPUT:

    try{
        int divideByZeroException = 5 / 0;
    } catch (Exception e){
        System.out.println("catch");
        return;    // also tried with break; in switch-case, got same output
    } finally {
        System.out.println("finally");
    }
    

    OUTPUT:

    catch
    finally
    

提交回复
热议问题