Consider I am developing a library. When this library encounters an exception it can't handle itself (e.g. a WebException
) it will wrap that exception to hide implementation details from clients and provide them a uniform way of exception handling.
Regarding the message of such an exception, what are the best practices / guidelines / do's /don'ts?
Option 1: Wrapper does not include anything
My personal favorite, each exception is responsible for its own message. The wrapper uses a more general wording than the one being expected from the inner exception.
try
{
// ...
}
catch (WebException ex)
{
throw new MyLibraryException("An error occured accessing a web ressource", ex);
}
Option 2: Display the inner message
What more could you want to say, than that what the inner exception has to say? Not sure whether this is viable...
try
{
// ...
}
catch (WebException ex)
{
throw new MyLibraryException(ex.Message, ex);
}
Option 3: Concatenate it
I don't believe that this is a good idea, but it came up in a discussion we had locally, so I want to present it as an option.
The outer exception will take care of concatenating inner exception messages.
try
{
// ...
}
catch (WebException ex)
{
string message = string.Format("An error occured accessing a web ressource: {0}", ex.Message);
throw new MyLibraryException(message, ex);
}
I feel that there must be clear guidelines on that topic (e.g. MSDN), but I was not able to find them. I already checked Best Practices for Exceptions, but for no avail.
Option 4: Don't care
From the comments:
do not waste time catching exceptions you cannot handle. Let the caller deal with it.
I don't think that this option is viable, because though I can't handle the exception myself I know that it can occur and I want to hide specifics from the caller (e.g. which exception type to handle?). This is important, because I could someday switch to another framework providing me with Web-Access and thus the exceptions could change. The wrapping helps to maintain the abstraction (IMHO).
edit: There seems to be a lot of confusion. I don't plan to apply this pattern to each and every exception. I will usually ignore or rethrow (throw;
) exceptions like FileNotFoundException
and many other core framework exceptions. However, there are cases when I want to hide and how am I supposed to do this in the best way possible?
Read this question as: If I had a good reason to nest exceptions, how should my messages look like?
Discussions on if you want to nest exceptions better belong here.