Confusedly by the contents of Exception.StackTrace

Suppose I have the following situation:

9 class Program 10 { 11 public static void WrapperMethod(Action func) 12 { 13 try 14 { 15 //throw new Exception("Case 1"); 16 func.Invoke(); 17 } 18 catch (Exception ex) 19 { 20 Console.WriteLine(ex.StackTrace); 21 } 22 } 23 24 static void Main(string[] args) 25 { 26 WrapperMethod(() => { throw new Exception("Case 2"); }); 27 } 28 } 

I run it and have the following output:

 at TestExceptions.Program.<Main>b__0() in c:\users\administrator\documents\visual studio 2010\Projects\TestExceptions\TestExceptions\Program.cs:line 26 at TestExceptions.Program.WrapperMethod(Action func) in c:\users\administrator\documents\visual studio 2010\Projects\TestExceptions\TestExceptions\Program.cs:line 16 

If I uncomment, throw a new exception ("Case 1"); exit:

 at TestExceptions.Program.WrapperMethod(Action func) in c:\users\administrator\documents\visual studio 2010\Projects\TestExceptions\TestExceptions\Program.cs:line 15 

So my question is why in the first case I see the full path, including the main function, while in the second case I do not see the same material. How can I display more complete information if the production code is similar to the second scenario.

+8
c # clr
source share
3 answers

In the first case, you call another method for an anonymous method, which is defined inside the Main method. Since an exception is thrown inside an anonymous method, it is pushed onto the call stack.

If you selected an exception in the WrapperMethod method, then the anonymous method will never be involved, so it will not be displayed in the call stack.

+1
source share

What you see in the stack trace is the compiler-generated name for the anonymous function that you pass to WrapperMethod. In this situation, it is impossible to get a "beautiful name" without using anonymous functions.

However, when you know this, it should not be difficult to β€œmentally parse” the distorted stack trace. You can recognize an anonymous function by name, which will look like <Main>b__0() , and you can say that it was declared inside the Program class, because it was here that the compiler decided to generate the function.

You do not lose stack information. If an exception is thrown inside the WrapperFunction, this will be the topmost frame of the stack. If an exception is thrown inside the method that calls the WrapperFunction, then (in this case anonymous) the method will be on top of the stack.

+7
source share

You see only the stack trace, nothing more.

The reason is that Lambda expressions are divided when they need to be executed, and before that they are only saved as data.

0
source share

All Articles