c# - 在异常处理中丢失原始堆栈跟踪
问题描述
我正在尝试正确处理异常,所以我一直在试验这段代码:
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 中出现我所期望的错误。我想这让我想知道:我如何确定在哪里/何时处理异常?似乎越早越好。
解决方案
这几乎可以按预期工作。解释如下:
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 ex
Method1("");
at [...].Method1(String text) in [...]:line 31 at [...].Main(String[] args) in [...]:line 10
如果您更改
throw ex
并throw
记录在 中捕获的异常Main
,则会保留第一个堆栈帧:at [...].Method2(String text) in [...]:line 45 at [...].Method1(String text) in [...]:line 31 at [...].Main(String[] args) in [...]:line 10
推荐阅读
- android - 切换 APN 并检查连接状态而不使用超时
- php - 从我的数据库中检索日期并在 Android Studio 中显示
- android - 将 Google Places API 插入 Fragment
- python - Pandas Groupby nlargest(唯一 nlargest)
- php - 二维数组 (ID, value) 中的复选框,$_POST 只能传输 ID 或值,但两者都需要 --- 做什么?
- powershell - 在 PowerShell 中使用 Selenium,无法捕获下拉列表
- heroku - 如何在heroku上部署vuejs + adonis-api only项目?
- c++ - 相同的结构可以在 C++ 中分配不同的内存大小吗?
- excel - Excel 公式如果返回 false
- dataweave - 如何根据 id 值合并 2 个字段并确保该字段是否不可用