2013-04-11 31 views
3

我在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' 

有没有根本就没有办法抓住它?

回答

0

并非所有错误都可以通过错误处理程序进行处理。 PHP核心中的致命错误将会停止处理更多指令,其中包括处理错误处理程序。从set_error_handler()文档:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

+1

但在他的输出,你可以看到,由于异常被创建的错误已被处理。问题是“为什么这个异常不可捕捉?”而不是“为什么这个错误难以处理?” – 2013-04-11 11:06:34

+0

@FrancoisBourgeois嗯,你是对的......我没有解释这一点。在ubuntu 12.04的PHP 5.3.10中,结果是不同的:'PHP致命错误:main():无法打开需要的'non \ existent \ file'(include_path ='。:/ usr/share/php:/ usr/share/pear')放在第20行的/ home/user/bla中(第20行是'require_once'行) – 2013-04-11 11:19:57