.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.
a source to share
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;
}
a source to share
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.
a source to share
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
}