问题
Is the following good practice and if not what should be done?
catch(Exception e)
{
throw new Exception(e.Message, e);
}
回答1:
No, this is not good practice if you're throwing another exception of the exact same type with the same message. In doing this, you complicate the stack trace and make debugging more of a pain.
If you're going to throw a new exception, it should differ from the original in some significant way. It should be another type, for example, or in some other way (like a more specific error message) clarify the reason for the exception. If you can't do either of those things, then simply rethrow the current exception using throw;
.
Or, even better, don't catch it at all. Rethrowing actually messes up the stack trace a tiny bit as well (the current frame's error location is set to the rethrow point rather than the spot where the exception happened), so if you don't have anything you personally have to do to handle the exception, then hands off -- just let it propagate and let the caller handle it.
回答2:
Just rethrow the exception that was caught, no need to create a new one.
catch(Exception e)
{
// Do some logging...
throw;
}
Some reading on rethrowing exceptions and implications on the stack trace for it: http://msdn.microsoft.com/en-us/library/ms182363(v=vs.100).aspx
回答3:
It depends on what you are trying to do. That exact code would be pointless, but something like
catch(Exception ex)
{
throw new ApplicationSpecificException("Error while doing something specific: " + contextualData, ex);
}
will help tremendously while debugging.
回答4:
If you need do something with the exception before re-throwing it, do this:
catch(Exception e)
{
// Additional handling here
throw;
}
Throw
by itself simply re-throws the current exception. If you don't need to handle it here, don't catch it in the first place.
Also, in your example you are catching any type of exception but throwing in its place a generic Exception
- probably not very useful.
回答5:
If the code really is just:
try
{
// something
}
catch(Exception e)
{
throw new Exception(e.Message, e);
}
Just delete the try/catch, it's not doing anything productive. Exchanging throw;
for the throw new...
is better, but still not productive.
if there's something else going on in the catch, do as Gromer details, and just use throw;
来源:https://stackoverflow.com/questions/12847637/throwing-a-new-exception-best-practice