Best practices for catching and re-throwing .NET exceptions

前端 未结 11 1589
野的像风
野的像风 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:15

    A few people actually missed a very important point - 'throw' and 'throw ex' may do the same thing but they don't give you a crucial piece of imformation which is the line where the exception happened.

    Consider the following code:

    static void Main(string[] args)
    {
        try
        {
            TestMe();
        }
        catch (Exception ex)
        {
            string ss = ex.ToString();
        }
    }
    
    static void TestMe()
    {
        try
        {
            //here's some code that will generate an exception - line #17
        }
        catch (Exception ex)
        {
            //throw new ApplicationException(ex.ToString());
            throw ex; // line# 22
        }
    }
    

    When you do either a 'throw' or 'throw ex' you get the stack trace but the line# is going to be #22 so you can't figure out which line exactly was throwing the exception (unless you have only 1 or few lines of code in the try block). To get the expected line #17 in your exception you'll have to throw a new exception with the original exception stack trace.

提交回复
热议问题