Reputation: 3231
Today I saw this piece of code:
get
{
Exception ex = null;
try
{
try { OnCurrentRead(); }
catch (Exception _) { ex = _; }
return base.Current;
}
finally { if (ex != null) throw ex; }
}
I wonder what is the need for such exception handling. Removing the stack trace?
An exception thrown from OnCurrentRead() is caught and assigned to a local variable. The property returns, but on the finally block, if the local variable is found to be assigned an exception object, this exception is thrown. Which basicaly
What would be the difference from the code below?
get
{
try
{
OnCurrentRead();
return base.Current;
}
catch(Exception ex) { throw ex; }
}
Or this one?
get
{
OnCurrentRead();
return base.Current;
}
UPDATE
It seems that the first code sample, ensures that base.Current will be called (it is a property) in every case, wether OnCurrentRead() throws an exception or not. Which means that it's bahavior is different than the two other code alternatives I provided, where base.Current wouldn't be called in case OnCurrentRead() throws an exception.
My question is wether this kind of exception handling is just used to achieve the call to base.Current or it has to do with some language specifications regardind returning a value and then throwing an exception on the finally block.
Upvotes: 1
Views: 443
Reputation: 17295
In the original code, if Current
is a property, its implementation will be executed prior to the exception being rethrown.
In the two alternatives you propose, any possible implementation of Current
will not be executed if OnCurrentRead()
throws an exception.
That said, IMHO, the original code has some serious code-smell. I'd prefer your second alternative (but technically it's not equivalent to the original).
Upvotes: 1