gpt4 book ai didi

php - 何时使用 ErrorException 与 Exception?

转载 作者:行者123 更新时间:2023-12-03 01:20:49 24 4
gpt4 key购买 nike

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

最佳答案

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

您应该避免直接使用太宽的Exception。使用特定的 Exception 对其进行子类化或使用 predefined SPL Exception

遵循您的编辑:Yes 扩展 Exception 而不是 ErrorException

关于php - 何时使用 ErrorException 与 Exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com