php的错误处理,try catch的问题
try catch是处理可以预知的错误,对于系统的fatal error无能为力,而且必须要通过throw 抛出异常才能捕获。
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
@inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
exit;
}
通过@符号可以抑制错误的显示,或者使用error_report(0)。
对以其他的未知错误,比如内存溢出等,php也没有很好的解决办法,不过有一个函数可以有好提示。
function shutdown_function()
{
$e = error_get_last();
print_r($e);
}
register_shutdown_function('shutdown_function');
new A;
这里由于A没有定义会报一个fatal error的错误。这个还是php程序执行玩的回调函数。我发现这个可以完成一个有趣的实验,实现程序报fatal错误继续运行的方法。
$star = 0;
function gg(){
global $star;
for($i=$star;$i<10;$i++){
if($i == 5){
echo "error".$i;
new A;
}
echo $i;
$star++;
}
}
gg();
// Continue execution
echo 'Hello World';
执行结果是01234error5
但是改为
function shutdown_function()
{
//$e = error_get_last();
//print_r($e);
global $star;
$star++;
gg();
}
register_shutdown_function('shutdown_function');
$star = 0;
function gg(){
global $star;
for($i=$star;$i<10;$i++){
if($i == 5){
echo "error".$i;
new A;
}
echo $i;
$star++;
}
}
gg();
// Continue execution
echo 'Hello World';
运行结果就是01234error56789
神奇吧
posted on 2012-09-06 16:11 kudosharry 阅读(1018) 评论(0) 编辑 收藏 举报