Why does catch in an action processing method truncate a stack trace?

Consider this small program. Ignore, if you like, the overall catch, I kept it briefly to try to illustrate the point:

private static void Main(string[] args) { Try(Fail); } private static void Fail() { var x = ((string)null).Clone(); } private static void Try(Action action) { try { action(); } catch (Exception exc) { Debug.WriteLine(exc.StackTrace); } } 

At startup, the following is created (with some path information deleted):

 at Scratch.Program.Fail() in Program.cs:line 27 at Scratch.Program.Try(Action action) in Program.cs:line 34 

My question is: why does the exception stack trace stop unwinding a chain of methods using the Try() method? I would expect it to open from the Main() method.

I was not able to find any documentation that stops throwing an exception bypassing Try() , so I would like to understand this.

+5
source share
2 answers

Exception.Stacktrace calls GetStackTrace , which will eventually call new StackTrace(this /* exception object */, true) . When used with these parameters, the stack trace will be evaluated for the exception point prior to the current method. You can check this by adding

 catch (Exception exc) { Debug.WriteLine(new StackTrace()); Debug.WriteLine(new StackTrace(exc, true)); } 

The second version is the stacktrace returned by exc.StackTrace , the first is the full stack from the current method to the entry point or the start of the stream.

+2
source

It:

 try { action(); } catch (Exception exc) { Debug.WriteLine(exc.StackTrace); } 

catches your exception inside Try and does not extend up to expand the stop code, it just swallows the exception. Therefore, you do not see Main as part of your stacktrace. If you want to see Main , leave catch your Main method:

 public static void Main(string[] args) { try { Try(Fail); } catch (Exception e) { } } 

And now you see:

in ConsoleApplication2.Program.Fail () in C: \ Users \ Yuval \ documents \ visual studio 14 \ Projects \ ConsoleApplication2 \ ConsoleApplication2 \ Program.cs: line 25 in ConsoleApplication2.Program.Try (action action) in C: \ Users \ Yuval \ documents \ visual studio 14 \ Projects \ ConsoleApplication2 \ ConsoleApplication2 \ Program.cs: line 30 in ConsoleApplication2.Program.Main (String [] args) in C: \ Users \ Yuval \ documents \ visual studio 14 \ Projects \ ConsoleApplication2 \ ConsoleApplication2 \ Program.cs: line 15

+4
source

Source: https://habr.com/ru/post/1207034/


All Articles