抓住所有(处理或未处理)异常 [英] Catch All (handled or unhandled) Exceptions

查看:140
本文介绍了抓住所有(处理或未处理)异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想捕获所有异常(处理或未处理)来记录它们。对于未处理的我使用ThreadExceptionEventHandler和UnhandledExceptionEventHandler,但我想捕获和异常,在try catch块有或没有(异常e)。可以继承异常类来创建一个常规事件?

I want to catch all exceptions raised (handled or unhandled) to log them. for unhandled i use ThreadExceptionEventHandler and UnhandledExceptionEventHandler but i want to catch and exceptions that are in try catch block with or without (Exception e). It's possible to inherit the exceptions class to create a general event?

推荐答案

从异常继承来提供自己的Exception类可以正常工作对于您在代码中生成的异常,您可以使用内部异常构造函数在链中携带内置异常。

Inheriting from Exception to provide your own Exception class would work fine for exceptions you generate in your code, and you could use the inner exception constructor to carry built in exceptions up the chain.

如果您是goig尝试, d需要替换所有的异常处理代码,也可能添加更多的块。我认为这不会比Peter McGrattan的方法好得多,但是在保存&检查原始的例外和重新抛出,例如记录是否已经在链中记录下来。

If you were goig to try that, you'd need to replace all of your exception handling code, and probably add a chunk more as well. I don't think it'd be substantially better than Peter McGrattan's approach, but it might allow you different options when preserving & examining the original exceptions and re-throwing, for example keeping a record of whether it has already been logged lower down the chain.

只是为了明确,可以使用:

Just to be explicit, it is possible to use:

catch (Exception e)
{
   log(e);
   throw;
}

这将重新启动原始异常。

which will rethrow the original exception.

这篇关于抓住所有(处理或未处理)异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆