代码之家  ›  专栏  ›  技术社区  ›  Zamboni

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

  •  4
  • Zamboni  · 技术社区  · 15 年前

    注意,我的目标是避免扩展方法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 回复  |  直到 15 年前
        1
  •  9
  •   jdehaan    15 年前

    有一个可怕的黑客 Marshal.GetExceptionPointers Marshal.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/

        2
  •  4
  •   Hans Passant    15 年前

    我想不出你为什么不这样做:

    private void Helper(bool exceptionWasCaught)
    {
        //...
    }
    
        3
  •  2
  •   Jesse C. Slicer    15 年前

    我不知道。这很麻烦,但它充分说明了开发人员的意图:

    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.
        }
    }
    
        4
  •  1
  •   DrFloyd5    9 年前

    为什么不更改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
        }
    }