异常捕获:什么时候不捕获它们? [英] Exception catching: when not to catch them?

查看:22
本文介绍了异常捕获:什么时候不捕获它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP 的 Zend 框架中为我的应用程序编写了许多小型库(一堆类).我也一直在库的方法本身中捕获这些异常并将它们记录到文件中.

I had been writing number of small libraries (bunch of classes) for my application inside PHP's Zend Framework. I had also been catching these exceptions inside the library's methods itself and logging them to a file.

然后突然我遇到了一个问题,即使用这些库的主应用程序即使在我预计它们会因致命错误而退出的情况下也不会因错误而退出.这样做的问题是下面的代码一直执行到最后——它不应该有.

Then suddenly I ran to an issue that my main application that was using these libraries would not quit due to errors even in situations I expected them to quit due to a fatal error. The problem with this was the code below kept executing till the end - which it should not have.

捕获并记录库类中的大多数错误(特殊情况除外)似乎不是一个好习惯.他们应该总是按原样抛出错误?这是一个正确的假设吗?

It seems like its not a good practice to catch and perhaps log majority (except in special cases) of the errors inside the library classes. They should always throw the error as it is? Would that be a correct assumption?

如果有人能为我回答这个问题,我将不胜感激.

I'd appreciate if anyone could answer this for me.

推荐答案

在任何语言中,异常的一般哲学是它们传达异常情况.您应该相应地使用它们.

The general philosophy of exceptions, in any language, is that they communicate exceptional circumstances. You should use them accordingly.

如果你最终用一个 try 块来包围每个函数调用,那就有问题了.异常被精确地设计为使错误处理合乎逻辑,并且不需要程序员跟踪所有可能的错误路径.因此,您应该在可以有意义地对异常做出响应的那些点捕获异常.

If you end up surrounding every function call with a try block, something is wrong. Exceptions are precisely designed to make error handling logical and not require the programmer to track all possible error paths. Therefore, you should catch exceptions precisely at those points where you can respond meaningfully to them.

如果您想不出比中止和传播错误更好的方法,那么捕获异常就没有意义了.另一方面,如果您能够对某些错误做出明智的反应,请抓住它们,然后重新抛出任何其他错误.

If you cannot think of anything better to do than to abort and propagate the error, then there's no point catching an exception. On the other hand, if there are some errors to which you can react sensibly, catch those, and rethrow anything else.

一个典型的例子是,如果您要处理大量文件.如果解析逻辑中的任何地方出现错误,您就无能为力,即使解析可能会中断许多函数调用.但是,在主循环中,您可以尝试解析每个文件,如果有异常,您可以捕获该异常,跳过该文件并继续下一个.

A typical example is if you're processing lots of files. If there's an error anywhere inside the parsing logic, there's nothing you can do, even though parsing may go down many function calls. However, at the main loop you can try parsing each file, and if there's an exception, you catch that, skip the file and continue with the next one.

如果您正在编写一个库函数,您可能希望在整个函数周围有一个最后的 try 块;不过,这在某种程度上取决于您.只需清楚地记录用户必须从您的库中获得哪些例外.

If you're writing a library function, you might want to have one final try block surrounding your entire function; that's somewhat up to you, though. Just document cleanly which exceptions the user has to expect from your library.

这篇关于异常捕获:什么时候不捕获它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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