Best practices for catching and re-throwing .NET exceptions

前端 未结 11 1616
野的像风
野的像风 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条回答
  •  Happy的楠姐
    2020-11-22 07:57

    FYI I just tested this and the stack trace reported by 'throw;' is not an entirely correct stack trace. Example:

        private void foo()
        {
            try
            {
                bar(3);
                bar(2);
                bar(1);
                bar(0);
            }
            catch(DivideByZeroException)
            {
                //log message and rethrow...
                throw;
            }
        }
    
        private void bar(int b)
        {
            int a = 1;
            int c = a/b;  // Generate divide by zero exception.
        }
    

    The stack trace points to the origin of the exception correctly (reported line number) but the line number reported for foo() is the line of the throw; statement, hence you cannot tell which of the calls to bar() caused the exception.

提交回复
热议问题