Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 417
Comic Sans MS Lover Avatar asked Jul 31 '13 20:07

Comic Sans MS Lover


2 Answers

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

like image 150
JB Nizet Avatar answered Oct 22 '22 12:10

JB Nizet


The finally block is executed always, unconditionally, as the last thing the try-catch-finally block does. Even if you execute Thread#stop against it, the finally block will still execute, just as if a regular exception ocurred.

Not just that, if you return from finally, that return value will trample over the return from either try or catch.

BTW Your first example is not just fine, but preferred. In the second example the reader must chase around the assignments to the variable, which is a tedious job and lets bugs slip through very easily.

like image 23
Marko Topolnik Avatar answered Oct 22 '22 14:10

Marko Topolnik