Throwing an exception in a catch section
I've got a new project. Every time you dealing with somebody else code it's an adventure.
Here is what I found:
try
{
.....
}
catch (InvalidOperationException e) {
throw e;
}
catch (Exception e)
{
throw;
}
Anybody has an idea why?
PS Thanks everybody. It really helps. Here are some good sources that you recommended:
Why catch and rethrow an exception in C#?
http://msdn.microsoft.com/en-us/library/0yd65esw.aspx
http://msdn.microsoft.com/en-us/开发者_Python百科library/ms229005.aspx
Because whoever has written this doesn't have any understanding of how exceptions work in .NET.
If you don't do anything with an exception, don't catch it.
The code you posted would better be written as:
.....
The real danger of this (other than being completely useless...) is that it modifies the call stack. Others have briefly mentioned it in comments, but it deserves to be called out specifically.
When you have throw ex;
, the previous call stack is blown away and replaced with the call stack at the point where throw ex;
is called. You almost never want to do this. I will often catch an exception, log it, then rethrow the exception. When doing that, you want to just use throw;
. This will preserve the original stack trace.
Makes no sense whatsoever to me, but not for the reason you might think.
Catching an exception is not the same thing as handling it. This try/catch block does no handling at all. I think a better, more honest, less verbose solution would have been to remove the try/catch and let the exceptions bubble up to where they can/should be dealt with.
i guess the application wants the outer method calling this to catch the exception instead but this is not the way it should be done, do check these references as they are somewhat similar
Why catch and rethrow an exception in C#?
http://winterdom.com/2002/09/rethrowingexceptionsinc
It is possible that they wanted to implement different handling for InvalidOperationException and other types of exceptions, so they wrote this code as a stub. But then this idea was abandoned so you see this code artifact.
you can improve this code by adding logging.
after every catch, log the information that you throw.
there are some opensource code available for logging.
精彩评论