一般异常处理策略。NET [英] General Exception Handling Strategy for .NET

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

问题描述

我已经习惯了有在每一个方法try / catch块。这样做的原因是为了让我能抓住每一个异常的违规点和记录它。我明白了,从我的阅读和与他人的谈话,这不是一个流行的观点。每个人都应该只抓到什么人是ppared处理$ P $。但是,如果我不明白,在违规的点,那么将有可能永远不能登录的违规行为,并了解它。注意:当我赶,不处理,我还是扔。这让我让异常传播到的东西,将处理它,但还是让我在违规的点记录它。

I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my reading and conversations with others, that this isn’t a popular view. One should only catch what one is prepared to handle. However, if I don’t catch at the point of infraction, then it would be possible to never log that infraction and know about it. Note: When I do catch and don’t handle, I still throw. This allows me to let the exception propagate to something that will handle it, yet still let me log it at the point of infraction.

所以...如何避免的try / catch在每一个方法,但仍然在该出现的点记录错误?

So... How does one avoid try/catch in every method, yet still log the error at the point at which it occurred?

推荐答案

没有,不抓住一切。异常传播越往上堆栈。所有你需要做的就是确保异常被捕获前,先要到堆栈的顶部。

No, don't catch everything. Exceptions propagate higher up on the stack. All you have to do is make sure that the exception is caught before it gets to the top of the stack.

这意味着,例如,你应该围绕一个事件处理程序与try / catch块的code。事件处理程序可以是在堆栈顶上。同为的ThreadStart处理程序,或从一个异步方法回调。

This means, for instance, that you should surround the code of an event handler with a try/catch block. An event handler may be the "top of the stack". Same for a ThreadStart handler or a callback from an asynchronous method.

您也想赶上层边界例外,但在这种情况下,你可能只是想换异常一层特有的异常。

You also want to catch exceptions on layer boundaries, though in that case, you might just want to wrap the exception in a layer-specific exception.

在ASP.NET的情况下,你可以决定让ASP.NET运行状况监视记录的异常给你。

In the case of ASP.NET, you may decide to allow ASP.NET Health Monitoring to log the exception for you.

但你肯定不会在任何时候需要抓住每方法例外。这是一个重大的反模式。我会大声反对你在code检查与那种异常处理。

But you certainly don't ever need to catch exceptions in every method. That's a major anti-pattern. I would loudly object to you checking in code with that kind of exception handling.

这篇关于一般异常处理策略。NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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