如何在运行时检测程序是否在抛出的异常下执行?

时间:2010-08-23 21:31:39

标签: c# .net exception

我可以在运行时检测到方法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.
}

4 个答案:

答案 0 :(得分:7)

有一个涉及Marshal.GetExceptionPointersMarshal.GetExceptionCode的可怕黑客攻击并不适用于所有平台:

public static Boolean IsInException()
{
   return Marshal.GetExceptionPointers() != IntPtr.Zero ||
          Marshal.GetExceptionCode() != 0;
}

从此页面:http://www.codewrecks.com/blog/index.php/2008/07/25/detecting-if-finally-block-is-executing-for-an-manhandled-exception/

答案 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
    }
}