Incorrect stacktrace by rethrow

前端 未结 12 1391
不知归路
不知归路 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:26

    OK, there seems to be a bug in the .NET Framework, if you throw an exception, and rethrow it in the same method, the original line number is lost (it will be the last line of the method).

    Fortunatelly, a clever guy named Fabrice MARGUERIE found a solution to this bug. Below is my version, which you can test in this .NET Fiddle.

    private static void RethrowExceptionButPreserveStackTrace(Exception exception)
    {
        System.Reflection.MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
          System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
        preserveStackTrace.Invoke(exception, null);
          throw exception;
    }
    

    Now catch the exception as usually, but instead of throw; just call this method, and voila, the original line number will be preserved!

提交回复
热议问题