我在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'
有沒有根本就沒有辦法抓住它?
但在他的輸出,你可以看到,由於異常被創建的錯誤已被處理。問題是「爲什麼這個異常不可捕捉?」而不是「爲什麼這個錯誤難以處理?」 – 2013-04-11 11:06:34
@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