如何在运行时检测程序是否在抛出异常的情况下执行?
问题描述:
我可以在运行时在方法Helper()中检测到程序执行是引发异常的结果吗?
Can I detect at runtime inside method Helper() that the program execution is the result of a thrown exception?
请注意,我的目标是避免扩展Helper()方法以将异常对象作为输入参数。
Note, my goal is to avoid extending method Helper() to take an exception object as a input pararmeter.
public void MyFunc1()
{
try
{
// some code here that eventaully throws an exception
}
catch( Exception ex )
{
Helper();
}
}
public void MyFunc2()
{
Helper();
}
private void Helper()
{
// how can I check if program execution is the
// result of a thrown exception here.
}
答
有一个可怕的骇客涉及 Marshal.GetExceptionPointers
和 Marshal.GetExceptionCode 不适用于所有平台,它是:
There is one horrible hack involving Marshal.GetExceptionPointers
and Marshal.GetExceptionCode
that doesn't work on all platforms here it is:
public static Boolean IsInException()
{
return Marshal.GetExceptionPointers() != IntPtr.Zero ||
Marshal.GetExceptionCode() != 0;
}