.Net Exception peeking. (Refresh)

try
  {
      throw a new exception ("test");
  }
  finally
  {
      // Inspect the exception ???? // Log (Exception);
  }

Is there a way to end up with a runtime exception?
I cannot use catch :-)

Thank you for your responses.
I cannot use catch because this is not my code (for refactoring).
We want to wrap a piece of code like this:

using(CriticalFlow(policy))  
{  
   //Not my code.  
   flow.Succeeded();  
}  

      

In the CriticalFlow finally block, we need to check for the exception, if it was not thrown, and warn anyone. Hope this will push the light towards the original question.

Thanks again.

+1


a source to share


7 replies


Exception helper;

try
{

}
catch (Exception ex)
{
    helper = ex;
}
finally
{
   if (helper != null)
   {
      process helper
   }
}

      



+7


a source


When you reach the finally block, the exception instance has already gone out of scope. The whole idea with try blocks is to have a place to check for exceptions. What you can do if you don't want to catch it is just change it:



try
{
    // some exception is thrown
}
catch (Exception ex)
{
    // do some logging or so
    throw;
}

      

+4


a source


No, you cannot. If you can change the rest of the code you could write:

Exception e = null;
try
{
    e = new Exception("test");
    throw e;
}
finally
{
    // Examine e
}

      

but there is nothing you can do "normally".

Could you wrap the whole thing up with a registration method? Delegates can be helpful here for example.

LogExceptions(delegate
    {
        try
        {
            throw new Exception("test"0;
        }
        finally
        {
            // Not logged yet
        }
    }
);

      

Where LogExceptions

will just try the specified action, catch any exceptions, log them and retrovit.

+2


a source


No, the exception is thrown on the stack until it hits the catch block.

Why can't you use catch?:? You can catch the exception you want to do with it and rethrow it if you want.

0


a source


Sorry, but this is not possible ...

0


a source


No, you cannot directly access the exception object in a block finally

. However, you can catch the exception in a block catch

, store it in a local variable, and then rethrow it using a statement throw;

.

0


a source


This code can clarify our intent:

using (CriticalFlow cf = new CriticalFlow())
            {
                // code which can throws
                cf.Completed();
            }

public class CriticalFlow : IDisposable
    {
        private bool _completed = false;

        public void Completed()
        {
            this._completed = true;
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (this._completed == false)
            {
               // can i peek the exception at this point?
            }
        }

        #endregion
    }

      

0


a source







All Articles