I want to implement custom exception handling in my library so that I know where an exception occurred, so I am doing this:
try
{
DoSomething();
}
catch(Exception ex)
{
//LibraryException refers to any exception in the libraries exception hierarchy
throw new LibraryException(ex.Message, ex);
}
-
Should this be avoided?
-
Does it have any performance implications?
-
What are the implications of catching, nesting and re-throwing exceptions?
The only potential problem is that you’re catching a non-specific
Exception, so not conforming to the exception handling guidelines.One of the following would be more conformant with these guidelines:
or:
As for performance, once an Exception has been thrown, something exceptional has happened, and you probably don’t care about the small additional overhead of wrapping it.
From comments:
I disagree with this, though it’s admittedly subjective. One example of a library that wraps exceptions is
SqlMembershipProvider, which wraps some specific exceptions in aProviderException, e.g.:but other exceptions such as
SqlExceptionthat a caller can’t be expected to handle are propagated unwrapped.