PHP 嵌套异常
phpserver side programmingprogramming更新于 2025/8/20 0:52:17
简介
try-catch 块可以嵌套至任意层级。异常将按出现的逆序处理,即最内层的异常首先处理。
示例
在以下示例中,内层 try 块检查两个变量中是否有一个非数字,如果是,则抛出用户定义的异常。如果分母为 0,外层 try 块将抛出 DivisionByZeroError。否则,将显示两个数字相除的结果。
示例
<?php
class myException extends Exception{
function message(){
return "error : " . $this->getMessage() . " in line no " . $this->getLine();
}
}
$x=10;
$y=0;
try{
if (is_numeric($x)==FALSE || is_numeric($y)==FALSE)
throw new myException("Non numeric data");
}
catch (myException $m){
echo $m->message();
return;
}
if ($y==0)
throw new DivisionByZeroError ("Division by 0");
echo $x/$y;
}
catch (DivisionByZeroError $e){
echo $e->getMessage() ."in line no " . $e->getLine();
}
?>
输出
显示以下输出
Division by 0 in line no 19
将任意一个变量更改为非数字值
error : Non numeric data in line no 20
如果两个变量都是数字,则打印它们的除法

