Incorrect stacktrace by rethrow

前端 未结 12 1387
不知归路
不知归路 2020-11-29 01:49

I rethrow an exception with \"throw;\", but the stacktrace is incorrect:

static void Main(string[] args) {
    try {
        try {
            throw new Exce         


        
12条回答
  •  眼角桃花
    2020-11-29 02:23

    You can preserve stack trace using

    ExceptionDispatchInfo.Capture(ex);
    

    Here is code sample:

        static void CallAndThrow()
        {
            throw new ApplicationException("Test app ex", new Exception("Test inner ex"));
        }
    
        static void Main(string[] args)
        {
            try
            {
                try
                {
                    try
                    {
                        CallAndThrow();
                    }
                    catch (Exception ex)
                    {
                        var dispatchException = ExceptionDispatchInfo.Capture(ex);
    
                        // rollback tran, etc
    
                        dispatchException.Throw();
                    }
                }
                catch (Exception ex)
                {
                    var dispatchException = ExceptionDispatchInfo.Capture(ex);
    
                    // other rollbacks
    
                    dispatchException.Throw();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.InnerException.Message);
                Console.WriteLine(ex.StackTrace);
            }
    
            Console.ReadLine();
        }
    

    The output will be something like:

    Test app ex
    Test inner ex
       at TestApp.Program.CallAndThrow() in D:\Projects\TestApp\TestApp\Program.cs:line 19
       at TestApp.Program.Main(String[] args) in D:\Projects\TestApp\TestApp\Program.cs:line 30
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at TestApp.Program.Main(String[] args) in D:\Projects\TestApp\TestApp\Program.cs:line 38
    --- End of stack trace from previous location where exception was thrown ---
       at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
       at TestApp.Program.Main(String[] args) in D:\Projects\TestApp\TestApp\Program.cs:line 47

提交回复
热议问题