Reputation: 5914
At some point during my career i learned that there is a major difference between doing
throw e
and
throw;
(The first version mangles the stack trace to be incomplete).
Is there a noteworthy difference between
catch(FormatException)
and
catch(FormatException e)
as well, which has a significant difference? (Apart from no option to hover an exception when debugging)
I am wondering if there is some technical reason to do this, because yesterday i noticed in some github repo (dnSpy), that the developer discarded the variable. I hope the answer to this is more exciting than "no - it's just shorter to write if you're not interested in the exception"
Upvotes: 2
Views: 174
Reputation: 23731
In Release mode, there is no difference in the IL generated by the compiler (no local variable is allocated for the exception in either case).
There is a slight difference when compiled in Debug mode (at least for me, compiling in VS 2017), where a local variable is allocated in the catch (SomeException e)
case, but not in the catch (SomeException)
case.
As such, the only compelling reason to remove the unused variable is to eliminate the compiler warning (which is a good enough reason for me).
Upvotes: 2
Reputation: 8183
The difference being one allows you to have access to the Exception
object as a variable, that way you can do different things e.g. a common approach would be logging.
So you could do something like
catch (FormatException e)
{
_log.LogError(e);
}
Note, the above will log and swallow the exception, it all depends on the use-case of your code.
Upvotes: 0
Reputation: 157068
Well, the CLR doesn't have to create the variable. That is about it. The exception has already been instantiated, so no gain there. It is just the allocation of one extra variable.
I think that what the developer drove to removing that variable is the compiler warning:
CS0168: The variable 'e' is declared but never used
Upvotes: 3