何时使用 ErrorException vs Exception?

php
2022-08-30 21:12:02

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 */ {}

它没有很好地记录下来,但它似乎被设计为从自定义错误处理程序中显式使用,如原始示例中所示,http://php.net/manual/en/class.errorexception.phpErrorException

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

答案 1

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

您应该避免直接使用太宽。使用特定或使用预定义的 SPL 异常对其进行子类化ExceptionException

要跟随您的编辑:是扩展而不是.ExceptionErrorException


答案 2

推荐