Why does catch in a method handling an Action truncate the stack trace?

前端 未结 2 416
有刺的猬
有刺的猬 2021-01-18 15:26

Consider this small program. Ignore, if you will, the generic catch, I\'ve kept it brief to try and illustrate the point:

private static void Main(string[] a         


        
2条回答
  •  滥情空心
    2021-01-18 15:56

    This:

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

    catches your exception inside Try, and doesn't propagate upwards to unwind the callstack, it simply swallows the exception. Therefor, you don't see Main as part of your stacktrace. If you want to see Main, leave the catch to your Main method:

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

    And now you see:

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

提交回复
热议问题