c# - C#:从变量中重新抛出异常,同时保留堆栈跟踪
问题描述
在我的代码库中,我有一些重试功能,将异常存储在变量中,最后在变量中抛出异常。想象这样的事情
Exception exc = null;
while(condition){
try {
// stuff
} catch (Exception e){
exc = e;
}
}
if (e != null){
throw e;
}
现在,由于这是一个throw e
语句而不是throw
语句,原始堆栈跟踪丢失了。是否有某种方法可以进行重新抛出以保留原始堆栈跟踪,或者我是否需要重组我的代码以便我可以使用throw
语句?
解决方案
这就是ExceptionDispatchInfo发挥作用的地方。
它位于System.Runtime.ExceptionServices
命名空间内。
class Program
{
static void Main(string[] args)
{
ExceptionDispatchInfo edi = null;
try
{
// stuff
throw new Exception("A");
}
catch (Exception ex)
{
edi = ExceptionDispatchInfo.Capture(ex);
}
edi?.Throw();
}
}
输出:
Unhandled exception. System.Exception: A
at EDI_Demo.Program.Main(String[] args) in C:\Users\...\Program.cs:line 16
--- End of stack trace from previous location where exception was thrown ---
at EDI_Demo.Program.Main(String[] args) in C:\Users\...\Program.cs:line 24
- 第 16 行
throw new Exception("A");
是调用的地方 - 第 24 行
edi?.Throw();
是调用的地方
推荐阅读
- xamarin - 如何将 Xamarin Forms Checkbox isChecked 绑定到动态布尔变量?
- swift - “模棱两可的使用”和受约束的泛型函数
- javascript - CSS登录功能如何在页面上保持静止
- turbo-c++ - Turbo C++ 文件处理:卡在输入循环中
- excel - 在 Excel 中的不同工作表上匹配名字和姓氏
- r - 如果与另一列中的值匹配,则将列中的值替换为“空白”
- python - 为什么我会收到 numpy.exp 的“ufunc 循环不支持 int 类型的参数 0”错误?
- dask - 将 numpy 数组发布到 dask.distributed.Queue 对象
- c++ - 当 DPI 感知、全屏和无框时,在 WM_NCACTIVATE 上擦除客户区
- swift - 不具有 GroupContainerIdentifier 的持久性 HTTPCookieStorage