问题 何时使用ErrorException vs Exception?


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");

2397
2017-11-19 15:49


起源



答案:


ErrorException 主要用于转换php错误(由...引发) 使用error_reporting) 至 Exception

你应该避免直接使用 Exception 太宽了。特定的子类 Exception 或使用 预定义的SPL异常

要关注你的编辑:是的 Exception 而不是 ErrorException


11
2017-11-19 15:57