最终的PHP异常处理
介绍
无论ry块中是否存在异常,finally块中的代码将始终执行。该块出现在catch块之后或代替catch块。
抓住并最终阻止
在下面的示例中,同时给出了catch和finally块。如果在try块中执行,则执行两者中的代码。如果没有异常,则仅执行finally块。
示例
<?php
function div($x, $y) {
if (!$y) {
throw new Exception('Division by zero.');
}
return $x/$y;
}
try {
echo div(10,0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
finally{
echo "This block is always executed\n";
}
//继续执行
echo "Execution continues\n";
?>输出结果
显示以下输出
Caught exception: Division by zero. This block is always executed Execution continues
在try块中更改语句,以免发生异常
示例
<?php
function div($x, $y) {
if (!$y) {
throw new Exception('Division by zero.');
}
return $x/$y;
}
try {
echo div(10,5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
finally{
echo "This block is always executed\n";
}
//继续执行
echo "Execution continues\n";
?>输出结果
显示以下输出
2 This block is always executed Execution continues
最终仅阻止
下面的示例有两个try块。其中之一直到最后才被封锁。它的try块调用div函数,该函数引发异常
示例
<?php
function div($x, $y){
try{
if (!$y) {
throw new Exception('Division by zero.');
}
return $x/$y;
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
try {
echo div(10,0) . "\n";
}
finally{
echo "This block is always executed\n";
}
//继续执行
echo "Execution continues\n";
?>输出结果
显示以下输出
Caught exception: Division by zero. This block is always executed Execution continues
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短