Throw VS rethrow : same result?

前端 未结 5 1640
隐瞒了意图╮
隐瞒了意图╮ 2021-02-20 11:26

refering to a lot of documentation on the net, particularly on SO, eg : What is the proper way to re-throw an exception in C#? there should be a difference between \"throw e;\"

5条回答
  •  佛祖请我去吃肉
    2021-02-20 11:54

    On a side note, I found a hack posted on a blog once (I've since lost the reference) that allows you to retain the call-stack on rethrow. This is mainly useful if you catch an Exception in one context (say, in a thread running an asynchronous operation) and want to rethrow it in another (say, in the other thread that launched the asynchronous operation). It makes use of some undocumented functionality included to allow preservation of stack traces across remoting boundaries.

        //This terrible hack makes sure track trace is preserved if exception is re-thrown
        internal static Exception AppendStackTrace(Exception ex)
        {
            //Fool CLR into appending stack trace information when the exception is re-thrown
            var remoteStackTraceString = typeof(Exception).GetField("_remoteStackTraceString",
                                                                     BindingFlags.Instance |
                                                                     BindingFlags.NonPublic);
            if (remoteStackTraceString != null)
                remoteStackTraceString.SetValue(ex, ex.StackTrace + Environment.NewLine);
    
            return ex;
        }
    

提交回复
热议问题