何时使用ErrorException而不是Exception?

19

PHP 5.1引入了ErrorException。这两个函数的构造方法不同。

public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
public __construct ([ string $message = "" [, int $code = 0 [, int $severity = 1 [, string $filename = __FILE__ [, int $lineno = __LINE__ [, Exception $previous = NULL ]]]]]] )

何时使用两者是否有区别?

我怀疑上述用例不正确:

<?php
class Data {
    public function save () {
        try {
            // do something
        } catch (\PDOException $e) {
            if ($e->getCode() == '23000') {
                throw new Data_Exception('Foo Bar', $e);
            }

            throw $e
        }
    }
}

class Data_Exception extends ErrorException /* This should not be using ErrorException */ {}

虽然没有很好地记录,但似乎 ErrorException 的设计是要从自定义错误处理器中显式地使用,就像原始示例中一样,http://php.net/manual/en/class.errorexception.php

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");
1个回答

23

ErrorException主要用于将php错误(由error_reporting引发)转换为Exception

您应该避免直接使用过于宽泛的Exception。而是应继承特定的Exception或使用预定义的SPL Exception

按照您的编辑要求:是扩展Exception而不是ErrorException


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接