Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

exception

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() to take an exception object as a input pararmeter.

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.
}
like image 599
Zamboni Avatar asked Aug 23 '10 21:08

Zamboni


3 Answers

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/

like image 172
jdehaan Avatar answered Sep 30 '22 18:09

jdehaan


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

private void Helper(bool exceptionWasCaught)
{
    //...
}
like image 23
Hans Passant Avatar answered Sep 30 '22 17:09

Hans Passant


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.
    }
}
like image 21
Jesse C. Slicer Avatar answered Sep 30 '22 18:09

Jesse C. Slicer