I have read a few of the other questions regarding C# Exception Handling Practices but none seem to ask what I am looking for.
If I implement my own custom Exception for a particular class or set of classes. Should all errors that relate to those classes be encapsulated into my exception using inner exception or should I let them fall through?
I was thinking it would be better to catch all exceptions so that the exception can be immediately recognized from my source. I am still passing the original exception as an inner exception. On the other hand, I was thinking it would be redundant to rethrow the exception.
Exception:
class FooException : Exception
{
//...
}
Option 1: Foo encasulates all Exceptions:
class Foo
{
DoSomething(int param)
{
try
{
if (/*Something Bad*/)
{
//violates business logic etc...
throw new FooException("Reason...");
}
//...
//something that might throw an exception
}
catch (FooException ex)
{
throw;
}
catch (Exception ex)
{
throw new FooException("Inner Exception", ex);
}
}
}
Option 2: Foo throws specific FooExceptions but allows other Exceptions to fall through:
class Foo
{
DoSomething(int param)
{
if (/*Something Bad*/)
{
//violates business logic etc...
throw new FooException("Reason...");
}
//...
//something that might throw an exception and not caught
}
}
Note Option 1: your
throw new FooException("Reason...");
won't be caught as it's outside try / catch blockthrow;
as it won't kill your stack. In Option 2 you still might do some processing inside catch and just callthrow;
to rethrow original exception with original stack.The purpose of custom exceptions is to provide detailed, contextual information to the stacktrace to aid in debugging. Option 1 is better because without it, you don't get the "origin" of the exception if it occurred "lower" in the stack.