What is the best way to bubble up exceptions from a library? When I implement an interface is it a good or bad practice to bug the calling party with exceptions that go about my implementation details? I have the following implementation where every implementation error is hidden away from the calling party. It looks to me as the cleanest way of implementing separation of concerns. But I read everywhere that you need to bubble up the exceptions untouched.
public class OneException : Exception
{
public OneException()
{
}
public OneException(string message): base(message)
{
}
public OneException(string message, Exception innerException)
: base(message, innerException)
{
}
}
And my library implementation:
public class MyLib : IMyLib
{
public int Divide(int a, int b)
{
try
{
if (b == 1) throw new OneException();
return a / b;
}
catch (OneException e)
{
throw new ApplicationException("Please do not divide by 1", e);
}
catch (Exception e) // divide by zero and others
{
throw new ApplicationException("Oops", e);
}
}
}
Choosing a right strategy for exception bubbling depends on two main factors:
If you want to provide more details about exception context, wrapping an exception into some more specific exception is a good strategy. The most obvious example here are business exceptions.
If you want to hide sensitive data from exception, you may consider replacing an exception. This approach is commonly used in services, when calling party is not trusted.
NOTE: You should never “swallow” exceptions, unless it’s not a part of a normal program flow.