How to detect if a program is executing under a thrown exception at runtime?

后端 未结 4 810
广开言路
广开言路 2020-12-18 07:54

Can I detect at runtime inside method Helper() that the program execution is the result of a thrown exception?

Note, my goal is to avoid extending method Helper()

相关标签:
4条回答
  • 2020-12-18 08:27

    Not that I'm aware of. This is cumbersome, but it fully delineates you as the developer's intent:

    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.
        }
    }
    
    0 讨论(0)
  • 2020-12-18 08:30

    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;
    }
    

    From this page: http://www.codewrecks.com/blog/index.php/2008/07/25/detecting-if-finally-block-is-executing-for-an-manhandled-exception/

    0 讨论(0)
  • 2020-12-18 08:32

    I cannot think of any reason why you wouldn't do it like this:

    private void Helper(bool exceptionWasCaught)
    {
        //...
    }
    
    0 讨论(0)
  • 2020-12-18 08:41

    I think you are overthinking this. If you have an exception, pass an exception. If you don't, don't.

    Why don't you want to change the signature of the Helper() method?

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题