Control flow of the try...catch...finally control structure
I have a try
...catch
...finally
block whose catch
rethrows the exception:
try
{
startBombCountdownAndRunAsFastAsYouCan();
}
catch (BombExplodedOnYourFaceException ex)
{
displayMessage("Hahaha! It blew up on your face!");
throw ex;
}
finally
{
cleanFloor();
}
displayMessage("Wow, you pulled it off!");
In this example, I need that cleanFloor()
be executed regardless of whether the exception was thrown or not. So the questio开发者_如何学编程n is: Is the finally
clause always executed, regardless of whether the exception is rethrown in the corresponding catch
clause?
Yes, this is the exact purpose that the finally concept was created.
Yes, the finally block will always be executed.
Also, as a side note if you're not going to use the explicitly caught exception, you should just use "catch { ... throw; }.
For reference:
http://www.codeproject.com/KB/architecture/exceptionbestpractices.aspx
The finally
is usually executed, but not always.
Consider the following Java program, where the finally
block is not executed:
package test;
public class TestFinally {
public static void main(String[] args) {
try {
throw new Exception ("throw!");
}
catch(Exception ex) {
System.out.println("catch!");
System.exit(0);
}
finally {
System.out.println("finally!");
}
}
}
It outputs:
catch!
The finally catch will only be executed if control is ever returned to the catch
, which as we can see is never guaranteed; determining if you execute the finally
is basically reduced to the Halting Problem.
In practice, the finally
block will usually be executed. Not always.
Peter Norvig's Java IAQ: Infrequently Answered Questions has a bit on this:
Q: The code in a finally clause will never fail to execute, right?
Well, hardly ever. But here's an example where the finally code will not execute, regardless of the value of the boolean choice:
try { if (choice) { while (true) ; } else { System.exit(1); } } finally { code.to.cleanup(); }
精彩评论