Throw VS rethrow : same result?

前端 未结 5 1745
隐瞒了意图╮
隐瞒了意图╮ 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:52

    It seems that the JIT optimizers does some work here. As you can see, the call stack in the second case is different than in the first case when you run the Debug build. However, in the Release build, both call stacks are identical due to the optimization.

    To see that this is related to the jitter you can decorate the methods with a MethodImplAttribute attribute:

    [MethodImpl(MethodImplOptions.NoOptimization)]
    private static void ThrowWithoutVariable()
    {
        try
        {
            BadGuy();
        }
        catch
        {
            throw;
        }
    }
    

    Note that the IL is still different for ThrowWithoutVariable and ThrowWithVariable:

    .method private hidebysig static void  ThrowWithVariable() cil managed
    {
      // Code size       11 (0xb)
      .maxstack  1
      .locals init ([0] class [mscorlib]System.Exception ex)
      .try
      {
        IL_0000:  call       void Ex::BadGuy()
        IL_0005:  leave.s    IL_000a
      }  // end .try
      catch [mscorlib]System.Exception 
      {
        IL_0007:  stloc.0
        IL_0008:  ldloc.0
        IL_0009:  throw
      }  // end handler
      IL_000a:  ret
    } // end of method Ex::ThrowWithVariable
    
    .method private hidebysig static void  ThrowWithoutVariable() cil managed
    {
      // Code size       11 (0xb)
      .maxstack  1
      .try
      {
        IL_0000:  call       void Ex::BadGuy()
        IL_0005:  leave.s    IL_000a
      }  // end .try
      catch [mscorlib]System.Object 
      {
        IL_0007:  pop
        IL_0008:  rethrow
      }  // end handler
      IL_000a:  ret
    } // end of method Ex::ThrowWithoutVariable
    

    Update to answer your follow-up question whether this is compliant with the CLI specification

    In fact it compliant, namely to allow for the JIT compiler to enable important optimizations. Annex F states on page 52 (emphasis by me):

    Some CIL instructions perform implicit run-time checks that ensure memory and type safety. Originally, the CLI guaranteed that exceptions were precise, meaning that program state was preserved when an exception was thrown. However, enforcing precise exceptions for implicit checks makes some important optimizations practically impossible to apply. Programmers can now declare, via a custom attribute, that a method is “relaxed”, which says that exceptions arising from implicit run-time checks need not be precise.

    Relaxed checks preserve verifiability (by preserving memory and type safety) while permitting optimizations that reorder instructions. In particular, it enables the following optimizations:

    • Hoisting implicit run-time checks out of loops.
    • Reordering loop iterations (e.g., vectorization and automatic multithreading)
    • Interchanging loops
    • Inlining that makes an inlined method as least as fast as the equivalent macro
    0 讨论(0)
  • 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;
        }
    
    0 讨论(0)
  • 2021-02-20 11:55

    I have tried running this code myself and the debug build works as I expected but I got the same result as you in the release build.

    I suspect what's happening is that the compiler inlining has simply replaced the BadGuy() call with throw new Exception(); because that's the only statement in BadGuy().

    If you switch off the 'Optimize code' option in the project properties -> Build screen, then both Release and Debug build produces the same result which shows BadGuy() at the top of the stack trace.

    0 讨论(0)
  • 2021-02-20 11:59

    Use a debug build and you will see the difference more clearly. With a debug build the first run will show the location as the throw ex line and the second as originating from the actual call to BadGuy. Obviously the 'problem' is the call to BadGuy - not the throw ex line and you'll chase fewer ghosts with the direct throw; statement.

    In a stack trace this shallow the benefits aren't as immediatley obvious, in a very deep stack you'll mask the actual source of the problem and loose some fidelity by manually throwing exception instead of using the built in re-throw statement.

    0 讨论(0)
  • 2021-02-20 12:02

    I can't replicate the problem -- using .NET 3.5 (32-bit) gives me the same results described in Bart's article.

    My guess is that the .NET 4 compiler/jitter -- or maybe it's the 64-bit compiler/jitter if this is happening under 3.5 too -- is inlining the BadGuy method into the calling methods. Try adding the following MethodImpl attribute to BadGuy and see if that makes any difference:

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
    private static void BadGuy()
    {
        //
        // Some nasty behavior.
        //
        throw new Exception();
    }
    
    0 讨论(0)
提交回复
热议问题