在PHP5中,应该使用Exceptions还是trigger_error / set_error_handler? [英] In PHP5, should I use Exceptions or trigger_error/set_error_handler?
问题描述
这两种方法的利弊是什么?有没有一个正确的方法(tm)?
What are the pros/cons of doing either way. Is there One Right Way(tm) ?
推荐答案
如果你想使用异常而不是整个应用程序的错误,你可以请执行 ErrorException 和自定义错误处理程序(请参阅示例错误处理程序的ErrorException页面)。这种方法的唯一缺点是,非致命错误仍然会抛出异常,除非被捕获,这些异常总是致命的。基本上,如果您的 error_reporting E_NOTICE 将会停止整个应用程序>设置不会压制他们。
If you want to use exceptions instead of errors for your entire application, you can do it with ErrorException and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an E_NOTICE
will halt your entire application if your error_reporting settings do not suppress them.
在我看来,使用ErrorException有几个好处:
In my opinion, there are several benefits to using ErrorException:
- 使用 set_exception_handler ,自定义异常处理程序将允许您显示漂亮的邮件,即使是错误。 / li>
- 它不会以任何方式中断现有的代码... trigger_error 等错误功能仍然可以正常工作。
- 这使得很难忽略触发
E_NOTICE
s和<$ c $的愚蠢编码错误c> E_WARNING s。 -
您可以使用
try
/捕获
以包装可能生成PHP错误的代码(不仅仅是异常),这是避免使用@
错误su的好方法ppress hack:
- A custom exception handler will let you display nice messages, even for errors, using set_exception_handler.
- It does not disrupt existing code in any way... trigger_error and other error functions will still work normally.
- It makes it really hard to ignore stupid coding mistakes that trigger
E_NOTICE
s andE_WARNING
s. You can use
try
/catch
to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the@
error suppression hack:
try {
$foo = $_GET['foo'];
} catch (ErrorException $e) {
$foo = NULL;
}
您可以将整个脚本封装在一个<$ c $如果您想在出现任何未捕获的错误时向用户显示友好的信息,请尝试 / catch
。 (仔细地做这个,因为只记录了错误和异常。)
You can wrap your entire script in a single try
/catch
block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)
这篇关于在PHP5中,应该使用Exceptions还是trigger_error / set_error_handler?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!