C#: Throwing Custom Exception Best Practices

2019-01-07 09:07发布

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
    }
}

8条回答
Juvenile、少年°
2楼-- · 2019-01-07 09:58

Note Option 1: your throw new FooException("Reason..."); won't be caught as it's outside try / catch block

  1. You should be only catching exceptions that you want to process.
  2. If you're not adding any additional data to the exception than use throw; as it won't kill your stack. In Option 2 you still might do some processing inside catch and just call throw; to rethrow original exception with original stack.
查看更多
时光不老,我们不散
3楼-- · 2019-01-07 10:02

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.

查看更多
登录 后发表回答