This is in response to a rejected feature request in PHP: Request 'finally' support for exceptions. What I didn't realize was that PHP doesn't allow you to comment on closed bugs. I thought it'd be a shame to have spent the time and effort writing up a response only to have it go to waste. Here's what I had to say, before the PHP bug system tried to silence me:
I believe try/finally is supposed to make the following pattern cleaner:
try {
danger_will_robinson();
} catch (RobotException, $exc) {
clean_up();
throw $exc; // let the exception bubble up so that the caller can take appropriate action
}
clean_up(); // make sure this happens even when there was no exception
try/finally provides two significant benefits here:
- you don't have to re-throw
- you don't have to copy cleanup code that's supposed to run regardless of whether an exception occurred
Here's what the above example would look like with try/finally
try {
danger_will_robinson();
} finally {
clean_up(); // one copy of your unconditional clean up code
}
I don't think there's anything wrong with this solution. To the contrary, it seems quite natural to me, and I believe others would find it fairly intuitive as well.
As far as why Java has this feature, I don't think it's because they needed a work-around for some other Java-specific oddity. It just makes sense whenever your language has exceptions.
No comments:
Post a Comment