首页 > 解决方案 > 未捕获的 PHP 异常

问题描述

我有以下代码:

set_error_handler(
    function ($errno, $errstr, $errfile, $errline, array $errcontex) {
        throw new Exception($errstr, 0);
    },
    E_ALL
);

class Foo
{
    public function asd(): int
    {
        return 0;
    }
}

class Bar
{
    public function asd(): int
    {
        return 1;
    }
}


$a = [
    1 => new Foo(),
    2 => new Bar(),
];

try {
    array_diff([], $a);
} catch (Throwable $exception)
{
    var_dump("11");
}

当我运行它时,它会导致以下错误:PHP Warning: Uncaught Exception: Object of class Foo could not be converted to string in /oms/bebe.php:5 Stack trace: .... 也就是说,尽管存在异常,但似乎没有被捕获set_error_handler。更奇怪的是,当我声明一个$a包含单个元素的数组时,

$a = [
    2 => new Bar(),
];

一切正常,即捕获异常并11输出。

怎么来的?以及如何用任意数组元素数量捕获该异常?

标签: phpexceptionphp-7.2

解决方案


推荐阅读