最终的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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便