异常是程序执行过程中出现的问题。在程序执行过程中,发生异常时,该语句后面的代码将不会被执行,PHP 将尝试查找第一个匹配的 catch 块。如果未捕获异常,则会发出 PHP 致命错误,并显示“未捕获异常”。
try { print "this is our try block"; throw new Exception(); }catch (Exception $e) { print "something went wrong, caught yah! n"; }finally { print "this part is always executed"; }
<?php function printdata($data) { try { //If var is six then only if will be executed if($data == 6) { // If var is zero then only exception is thrown throw new Exception('Number is six.'); echo "</p><p> After throw (It will never be executed)"; } } // When Exception has been thrown by try block catch(Exception $e){ echo "</p><p> Exception Caught", $e->getMessage(); } //this block code will always executed. finally{ echo "</p><p> Final block will be always executed"; } } // Exception will not be rised here printdata(0); // Exception will be rised printdata(6); ?>
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
要处理异常,程序代码必须位于 try 块内。每次尝试必须至少有一个相应的 catch 块。多个catch块可用于捕获不同类别的异常。
以上是PHP中的异常处理是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!