解析PHP中Exception异常机制 |
异常的基本使用当异常被抛出时,其后的代码不会继续执行,PHP 会尝试查找匹配的 "catch" 代码块 。 <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception checkNum(2); ?> 上面的代码会获得类似这样的一个错误: PHP Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in /home/wangkongming/babytree/test/php/php_ob/3.php:7 Stack trace: #0 /home/wangkongming/babytree/test/php/php_ob/3.php(12): checkNum(2) #1 {main} thrown in /home/wangkongming/babytree/test/php/php_ob/3.php on line 7 Try, throw 和 catch要避免上面例子出现的错误,我们需要创建适当的代码来处理异常 。 <?php //create function with an exception function checkNum($number) { if($number>1) { throw new Exception("Value must be 1 or below"); } return true; } //trigger exception try{ checkNum(2); echo "If you see this ,the number is 1 or below"; }catch(Exception $e) { echo 'Message: '.$e -> getMessage(); } ?> 运行上面的代码:
例子解释:上面的代码抛出了一个异常,并捕获了它: 到此这篇关于解析PHP中Exception异常机制的文章就介绍到这了,更多相关PHP中Exception异常内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! |