Java - If I return in a catch block, will the finally block be executed?

Comic Sans MS Lover picture Comic Sans MS Lover · Jul 31, 2013 · Viewed 12.1k times · Source

This is what I'm trying to do:

try {

    //code
} catch (Exception e) {

    return false;
} finally {

    //close resources
}

Will this work? Is it bad practice? Would it be better doing this:

boolean inserted = true;

try {

    //code
} catch (Exception e) {

    inserted = false;
} finally {

    //close resources
}

return inserted;

Answer

JB Nizet picture JB Nizet · Jul 31, 2013

Yes, it will. The only things that can prevent a finally block to execute (AFAIR) are System.exit(), and an infinite loop (and a JVM crash, of course).