Throw VS rethrow : same result?

烂漫一生 提交于 2019-12-04 02:27:13

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();
}

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.

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

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.

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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!