例外是在程序执行期间出现的问题。在程序执行期间,如果发生异常,则不会执行该语句之后的代码,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 { //如果var为6,则仅在执行时 if($data == 6) { //如果var为零,则仅引发异常 throw new Exception('Number is six.'); echo "\n After throw (It will never be executed)"; } } //当try块引发Exception- catch(Exception $e){ echo "\n Exception Caught", $e->getMessage(); } //该块代码将始终执行。 finally{ echo "\n Final block will be always executed"; } } //这里不会出现异常 printdata(0); //异常会出现 printdata(6); ?>
输出结果
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
要处理异常,程序代码必须在try块内。每次尝试都必须至少有一个各自的捕获块。可以使用多个catch块来捕获不同类别的异常。