I saw some code like this:
try
{
db.store(mydata);
}
finally
{
db.cleanup();
}
I thought try
Why does this code do it this way?
Because apparently the code doesn’t know how to handle exceptions at this level. That’s fine – as long as one of the callers does, i.e. as long as the exception gets ultimately handled somewhere.
Often, low-level code cannot react appropriately to exceptions because the user needs to be notified, or the exception must be logged, or another strategy has to be tried. Low-level code performs one function only and doesn’t know about higher-level decision making.
But the code still needs to clean up its resources (because if it doesn’t, they would leak), so it does just that in the finally
clause, making sure that it always happens, whether an exception was thrown or not.