Best practices for catching and re-throwing .NET exceptions

前端 未结 11 1595
野的像风
野的像风 2020-11-22 07:15

What are the best practices to consider when catching exceptions and re-throwing them? I want to make sure that the Exception object\'s InnerException

11条回答
  •  自闭症患者
    2020-11-22 08:08

    Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw() and a plain throw, so here it is. However, some people have noticed the problem with throw.

    The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw() (only available from .Net 4.5).

    Below there are the cases necessary to test this:

    1.

    void CallingMethod()
    {
        //try
        {
            throw new Exception( "TEST" );
        }
        //catch
        {
        //    throw;
        }
    }
    

    2.

    void CallingMethod()
    {
        try
        {
            throw new Exception( "TEST" );
        }
        catch( Exception ex )
        {
            ExceptionDispatchInfo.Capture( ex ).Throw();
            throw; // So the compiler doesn't complain about methods which don't either return or throw.
        }
    }
    

    3.

    void CallingMethod()
    {
        try
        {
            throw new Exception( "TEST" );
        }
        catch
        {
            throw;
        }
    }
    

    4.

    void CallingMethod()
    {
        try
        {
            throw new Exception( "TEST" );
        }
        catch( Exception ex )
        {
            throw new Exception( "RETHROW", ex );
        }
    }
    

    Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw new Exception( "TEST" ) line.

    However, case 3 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw call. This means that if the throw new Exception( "TEST" ) line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.

    Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.

提交回复
热议问题