异常是程序执行过程中出现的问题。在程序执行过程中,发生异常时,该语句后面的代码将不会被执行,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"; }
example 的中文翻译为:示例<?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 "
after throw (it will never be executed)"; } } // when exception has been thrown by try block catch(exception $e){ echo "
exception caught", $e->getmessage(); } //this block code will always executed. finally{ echo "
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 executedexception caughtnumber is six.final block will be always executed
注意要处理异常,程序代码必须位于 try 块内。每次尝试必须至少有一个相应的 catch 块。多个catch块可用于捕获不同类别的异常。
以上就是php中的异常处理是什么?的详细内容。