首页 > 解决方案 > 在异常处理中丢失原始堆栈跟踪

问题描述

我正在尝试正确处理异常,所以我一直在试验这段代码:

 class MainClass
    {
        private static Logger logger = new Logger();

        public static void Main(string[] args)
        {

            try
            {
                Method1("");
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }

        private static void Method1(string text)
        {
            try
            {
                Method2(text);
            }
            catch (Exception ex)
            {
                logger.Write(ex);
                throw ex;
            }
            
        }

        private static void Method2(string text)
        {
            try
            {
                Console.WriteLine(text[0]);
            }
            catch (Exception ex)
            {
                logger.Write(ex);
                throw;
            }
        }
    }

我注意到在 Method2 中记录的异常中,它表明错误是在 try 块中引发的"Console.WriteLine(text[0])"::

System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at ExceptionHandlingTest.MainClass.Method2 (System.String text) [0x00002] in /ExceptionHandlingTest/Program.cs:40

但是在Method1中记录的异常中,它只显示它被抛出在catch块中throw;::

System.IndexOutOfRangeException: Index was outside the bounds of the array.
  at ExceptionHandlingTest.MainClass.Method2 (System.String text) [0x00020] in /ExceptionHandlingTest/Program.cs:45 
  at ExceptionHandlingTest.MainClass.Method1 (System.String text) [0x00002] in //ExceptionHandlingTest/Program.cs:26 

我在这里做错了什么,还是它应该工作的方式?当我进入 Method1 时,InnerException 为空。

我看到如果我从 Method2 中删除 try/catch,Method1 中的异常会在 Console.WriteLine 中出现我所期望的错误。我想这让我想知道:我如何确定在哪里/何时处理异常?似乎越早越好。

标签: c#exception

解决方案


这几乎可以按预期工作。解释如下:

  • Method2使用堆栈跟踪记录异常Console.WriteLine(text[0]);

    at [...].Method2(String text) in [...]:line 40
    
  • Method1使用堆栈跟踪记录异常,该throw异常catch位于Method2. 然后,下一个堆栈帧在Method2(text);调用中Method1(堆栈跟踪保持不变,因为您使用了throw,而不是throw ex):

    at [...].Method2(String text) in [...]:line 45
    at [...].Method1(String text) in [...]:line 26
    
  • Main中,您没有记录异常;您只是在显示隐藏.Message您正在发生的事情的属性。如果您记录异常并检查其跟踪跟踪,您会发现它从 开始,然后下一帧在对 的调用处。换句话说,缺少堆栈帧:throw exMethod1("");

    at [...].Method1(String text) in [...]:line 31
    at [...].Main(String[] args) in [...]:line 10
    

    如果您更改throw exthrow记录在 中捕获的异常Main,则会保留第一个堆栈帧:

    at [...].Method2(String text) in [...]:line 45
    at [...].Method1(String text) in [...]:line 31
    at [...].Main(String[] args) in [...]:line 10
    

推荐阅读