PHP 中的异常处理是什么?
phpprogrammingserver side programming更新于 2025/10/7 6:52:17
异常是指程序执行过程中出现的问题。程序执行过程中,如果发生异常,语句后面的代码将不会被执行,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 语句
if($data == 6) {
// 如果 var 为 0,则仅抛出异常
throw new Exception('Number is six.');
echo &"
抛出后 (永远不会执行)";
}
}
// 当 try 块抛出异常时
catch(Exception $e){
echo &"
Exception Caught&", $e->getMessage();
}
//此块代码将始终执行。
finally{
echo "
final 块将始终执行";
}
}
// 此处不会引发异常
printdata(0);
// 将会引发异常
printdata(6);
?>
输出
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed

