PHP最终与返回之间的交互
介绍
当try块或catch块(或两者)都包含return语句时,finally块会有特殊的行为。通常return语句使程序的控制返回到调用位置。但是,如果函数带有带有return的try/catch块,则finally块中的语句将在返回之前首先执行。
示例
在下面的示例中,div()函数具有try-catch-finally构造。try块无一例外会返回除法结果。如果发生异常,catch块将返回错误消息。但是,无论哪种情况,都首先执行finally块中的语句。
示例
<?php
function div($x, $y){
try {
if ($y==0)
throw new Exception("Division by 0");
else
$res=$x/$y;;
return $res;
}
catch (Exception $e){
return $e->getMessage();
}
finally{
echo "This block is always executed\n";
}
}
$x=10;
$y=0;
echo div($x,$y);
?>输出结果
显示以下输出
This block is always executed Division by 0
将$y的值更改为5。显示以下输出。
This block is always executed 2