异常捕捉:何时不抓住他们? [英] Exception catching: when not to catch them?

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

问题描述

我在PHP的Zend Framework中为我的应用程序编写了一些小型库(一堆类)。我也在库中的方法本身捕捉到这些异常并将其记录到一个文件中。

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.

如果你最终用$ code> 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天全站免登陆