最终的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