我可以在运行时检测到方法Helper()中程序执行是抛出异常的结果吗?
注意,我的目标是避免扩展方法Helper()将异常对象作为输入参数。
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.
}
答案 0 :(得分:7)
有一个涉及Marshal.GetExceptionPointers
和Marshal.GetExceptionCode
的可怕黑客攻击并不适用于所有平台:
public static Boolean IsInException()
{
return Marshal.GetExceptionPointers() != IntPtr.Zero ||
Marshal.GetExceptionCode() != 0;
}
答案 1 :(得分:4)
我想不出你为什么不这样做的原因:
private void Helper(bool exceptionWasCaught)
{
//...
}
答案 2 :(得分:2)
不是我知道的。这很麻烦,但它完全描绘了您作为开发人员的意图:
private bool inException = false;
public void MyFunc1()
{
try
{
inException = false;
// some code here that eventaully throws an exception
}
catch( Exception ex )
{
inException = true;
Helper();
}
}
public void MyFunc2()
{
inException = false;
Helper();
}
private void Helper()
{
// how can I check if program execution is the
// result of a thrown exception here.
if (inException)
{
// do things.
}
}
答案 3 :(得分:1)
我认为你是在思考这个问题。如果您有异常,请传递异常。如果不这样做,请不要。
为什么不想更改Helper()方法的签名?
public void MyFunc1()
{
try
{
// some code here that eventually throws an exception
}
catch( Exception ex )
{
Helper(ex);
}
}
private void Helper(Exception ex = null)
{
// result of a thrown exception here.
if (ex!=null)
{
// do things.
} else {
// do other things
}
}