【问题标题】:Could not catch exceptions created from errors无法捕获由错误创建的异常
【发布时间】:2013-04-11 09:59:34
【问题描述】:

我在 Ubuntu 12.10 上运行 PHP 5.4.12。

我正在使用错误处理程序将 PHP 错误转换为异常,以便我可以处理它们。但是,我发现虽然我可以将错误转化为异常,但似乎根本没有办法捕获异常。

下面是一些简单的演示代码:

<?php 
class CErrorException extends Exception {}

function handleError($level, $message, $file, $line){

    if( error_reporting() != 0){
        throw new CErrorException($message, $level);
    }
}

function handleException(Exception $exception){
    var_dump('Exception handled at global level');
}

set_error_handler('handleError');

set_exception_handler('handleException');

try {
    require_once('non\existent\file'); //Will generate an error and cause an exception to be thrown.
} catch (Exception $e) {
    var_dump("let's deal with the exception");
}

不幸的是,在这种情况下,我永远无法捕获引发的异常,这使得很难从在不存在或不可读的文件上使用 require_once 引起的问题中恢复。

我收到以下 2 个错误:

Warning: Uncaught exception 'CErrorException' with message 'require_once(non\existent\file): failed to open stream: Invalid argument' in /work/test.php:7 Stack trace: #0 /work/test.php(20): handleError(2, 'require_once(no...', '/work/test.php', 20, Array) #1 /work/test.php(20): require_once() #2 {main} thrown in /work/test.php on line 7

Fatal error: main(): Failed opening required 'non\existent\file'

就没有办法抓住它吗?

【问题讨论】:

    标签: php exception exception-handling


    【解决方案1】:

    并非所有错误都可以使用错误处理程序进行处理。 PHP 核心中的致命错误将停止处理进一步的指令,包括处理您的错误处理程序。来自set_error_handler()的文档:

    以下错误类型无法用用户定义的方式处理 功能:E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、 E_COMPILE_ERROR、E_COMPILE_WARNING 和大部分 E_STRICT 在 调用 set_error_handler() 的文件。

    【讨论】:

    • 但是在他的输出中你可以看到,自从创建异常后,错误就得到了处理。问题是“为什么这个异常不能被捕获?”而不是“为什么这个错误无法处理?”
    • @FrancoisBourgeois 嗯,你是对的......我对此没有任何解释。在 ubuntu 12.04 中的 PHP 5.3.10 上,结果有所不同:PHP Fatal error: main(): Failed opening required 'non\existent\file' (include_path='.:/usr/share/php:/usr/share/pear') in /home/user/bla on line 20(第 20 行是 require_once 行)
    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2015-06-11
    • 2018-11-13
    • 2014-03-21
    • 2010-10-29
    相关资源
    最近更新 更多