定制异常处理程序 [英] Custom exception handler

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

问题描述

我正在需要编写一个自定义异常处理程序...



我的应用程序可能会抛出不同种类的异常,我希望他们所有这些都由单个处理程序处理(所以我不需要使用数千个try-catch块)。



我尝试使用AppDomain的UnhandledException处理程序,但是似乎当一个异常被捕获时,应用程序将不可避免地被关闭。



所以,有没有办法完成我的想法?



编辑:



感谢您的快速回复,但我想让您更好地了解我的情况:例如,引发自定义异常(可逆)的类。现在,这个类,被多个其他类调用,所以我需要在每个单独的一个上写一个try-catch块(或者至少这是你的回复让我想到的)..



所以,这里需要一个能够捕获它们的处理程序。

解决方案

您应该在您的代码中最好地处理它们的之间捕获特定异常。这不应该导致数千个try-catch块,而是应该找到本地化的异常处理区域。



我倾向于在服务边界处理异常,例如,当与数据库或文件系统进行交互时。在这些服务边界,您可以处理异常并执行一些逻辑恢复。



如果您发现自己编写的try-catch块,其中catch不添加值,则无法帮助您的代码恢复,那么您不会通过捕获异常来增加价值!


I'm in the needing of write a custom exception handler...

MY application is probably going to throw different kind of exceptions, and I would like they all get handled by a single handler (so that I don't need to use thousands of "try-catch" blocks).

I tried with the AppDomain's UnhandledException handler, but it seems that, when an exception is caught, the application will inevitably be closed.

So, is there any way I could accomplish my idea?

EDIT:

Thank you for your rapid replies, but I'd like to make you understand better my situation: I have, for example, a class which throws a custom exception (reversible). Now, this class, is called by multiple other class, so I would need to write a try-catch block on every single one of them (or at least this is what your replies make me think about)..

So, here comes the needing of have an handler capable of catch them all...

解决方案

You should catch specific exceptions at the point in your code where you are best able to handle them. This should not result in thousands of try-catch blocks, rather, you should find localised areas of exception handling.

I tend to handle exceptions at service boundaries, for example, when interacting with databases or file-systems. At these service boundaries you can handle an exception and perform some logical recovery.

If you find yourself writing try-catch blocks where the catch does not add value, does not help your code recover, then you are not adding value by catching the exception!

这篇关于定制异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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