We've seen plenty of questions about when and why to use try
/catch
and try
/catch
/finally
. And I know there's definitely a use case for try
/finally
(especially since it is the way the using
statement is implemented).
We've also seen questions about the overhead of try/catch and exceptions.
The question I linked to, however, doesn't talk about the overhead of having JUST try-finally.
Assuming there are no exceptions from anything that happens in the try
block, what's the overhead of making sure that the finally
statements get executed on leaving the try
block (sometimes by returning from the function)?
Again, I'm asking ONLY about try
/finally
, no catch
, no throwing of exceptions.
Thanks!
EDIT: Okay, I'm going to try to show my use case a little better.
Which should I use, DoWithTryFinally
or DoWithoutTryFinally
?
public bool DoWithTryFinally()
{
this.IsBusy = true;
try
{
if (DoLongCheckThatWillNotThrowException())
{
this.DebugLogSuccess();
return true;
}
else
{
this.ErrorLogFailure();
return false;
}
}
finally
{
this.IsBusy = false;
}
}
public bool DoWithoutTryFinally()
{
this.IsBusy = true;
if (DoLongCheckThatWillNotThrowException())
{
this.DebugLogSuccess();
this.IsBusy = false;
return true;
}
else
{
this.ErrorLogFailure();
this.IsBusy = false;
return false;
}
}
This case is overly simplistic because there are only two return points, but imagine if there were four... or ten... or a hundred.
At some point I would want to use try
/finally
for the following reasons:
this.Working
is set to false
.So hypothetically, given performance concerns, maintainability, and DRY principles, for what number of exit points (especially if I can assume that all inner exceptions are caught) do I want to incur whatever performance penalty is associated with try
/finally
?
EDIT #2: I changed the name of this.Working
to this.IsBusy
. Sorry, forgot to mention this is multithreaded (though only one thread will ever actually call the method); other threads will be polling to see if the object is doing its work. The return value is merely success or failure for if the work went as expected.