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).
Java - If I return in a catch block, will the finally block be executed? [duplicate]
-
04-06-2022 - |
Pregunta
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;
Solución
Otros consejos
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.
Both are approximately the same. However, be careful with the following case:
int i = 0;
try
{
//code
}
catch(Exception e)
{
return i;
}
finally
{
i = 1;
}
0
is what will be returned.
I just wanted to add that it's described in the specs:
If the catch block completes abruptly for reason R, then the finally block is executed.
where of course
It can be seen, then, that a return statement always completes abruptly.