How to determine if a program is executing at runtime while an exception is executing?

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

Please note: my goal is to avoid extending the Helper () method to accept an exception object as an input parameter.

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.
}
+3
source share
4 answers

There is one terrible hack, including Marshal.GetExceptionPointersand Marshal.GetExceptionCodewhich does not 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/

+6

, :

private void Helper(bool exceptionWasCaught)
{
    //...
}
+3

Not that I knew. This is cumbersome, but it completely defines you as the intention of the developer:

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.
    }
}
+2
source

I think you are thinking too much about it. If you have an exception, send an exception. If you do not, do not do this.

Why don't you 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
source

Source: https://habr.com/ru/post/1761200/


All Articles