Typically when I throw an exception, catch it, and print out the stacktrace, I get to see the call where the exception was thrown, the call that led to that, the call that led to that, and so on back to the root of the entire program.
Now it’s only showing me the call where the exception is being caught, not where it’s being thrown. I can’t figure out what’s changed to lead to this. Here’s my program:
using System;
class foo {
static void Main(string[] args) {
try { f(); }
catch (Exception e) { Console.WriteLine(e.StackTrace); }
}
static void f() { g(); }
static void g() { throw new Exception(); }
}
And here’s what gets printed out:
at foo.Main(String[] args) in C:\Projects\test\root.cs:line 5
What I expected would be something like this:
at foo.g...
at foo.f...
at foo.Main...
Any ideas?
It still shows where the exception was thrown, not where it was caught. But thanks to optimizations that might not be where you expect it to be thrown.
Most likely the function that throws the exception was inlined into the calling function.
In this case I expect the JIT optimizer to be responsible. By default it doesn’t optimize when running in a debugger, but optimizes and thus inlines the method when not running in a debugger. I’m not sure if a Debug build has an effect on inlining.
If you add
[MethodImpl(MethodImplOptions.NoInlining)]to a function it won’t be inlined and your stack-trace should be as expected.