开发者

Catching handled exceptions

Hey:)

Is there any way to catch a handled exception globally? I know we can catch unhandled exceptions with " AppDomain.CurrentDomain.UnhandledException" and "Applica开发者_JS百科tion.ThreadException", but I would like to add some handling to the exceptions I already caught (such as writing to log, etc)

thanks


In general, you probably want to catch exceptions at the lowest possible level in your code. The closer they're handed relative to where the exception occurs, the better chance that you have to fix the problem that caused them.

If you can't take any corrective action at this level that has a hope of fixing the problem causing the exception, you should not be handling it at all. Just let the exception bubble up, and handle it globally like you want.

That being said, if you've have handled the exception at a lower level, the only way you're going to be able to catch it at a higher level is if you rethrow it from the Catch block at the lower level.
So, for example:

try
{
   //your code
}
catch (SomeException e)
{
   //take any relevant handling measures

   //rethrow the exception
   throw; 
}

Of course, this would technically mean that the exception is unhandled by this Try/Catch block at the lower level, but that's the only way you're going to have anything to catch at a higher level.

For more information on rethrowing exceptions, see:

  • Why Re-throw Exceptions?
  • http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx
  • http://msdn.microsoft.com/en-us/library/xhcbs8fz.aspx


You can rethrow same exception and catch it in calling module / logging module and then log it. For example :

private void DivideByZero()
{
try
{
    int x = 2/0;
}
cath(Exception ex)
{
    Console.Writeline(ex.ToString());
    throw;
}
}

void Main(string[] a)
{
    try
    {
       DivideByZero();
    }
    catch(Exception x)
    {
        // write logging code here .. 
    }

}


No, there is not global exception event. That would be very dangerous, you would catch all sorts of internal exceptions from other modules that was not ment for public use. It would also potentially drown your logs with exceptions.

You should be more structured about your exception handling to achieve the same effect. Encapsulate the actual handling of exceptions and do minimal work in the actual catch block. Either by just have a "HandleException" method somewhere that you pass every exception too. You might also have a look at the Exception Handling block in Enterprise library.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜