使用多个 catch 块进行 PHP 异常处理
phpserver side programmingprogramming更新于 2025/7/19 3:52:17
简介
PHP 允许在 try 块后使用一系列 catch 块来处理不同的异常情况。可以使用各种 catch 块来处理预定义异常和错误以及用户定义的异常。
示例
以下示例使用 catch 块来处理 DivisioByZeroError、TypeError、ArgumentCountError 和 InvalidArgumentException 等异常情况。此外,还有一个 catch 块用于处理一般异常。
示例
<?php
declare(strict_types=1);
function divide(int $a, int $b) : int {
return $a / $b;
}
$a=10;
$b=0;
try{
if (!$b) {
throw new DivisionByZeroError('Division by zero.');}
if (is_int($a)==FALSE || is_int($b)==FALSE)
throw new InvalidArgumentException("Invalid type of arguments");
$result=divide($a, $b);
echo $result;
}
catch (TypeError $x)//如果参数类型不匹配{
echo $x->getMessage();
}
catch (DivisionByZeroError $y) //如果分母为 0{
echo $y->getMessage();
}
catch (ArgumentCountError $z) //如果参数数量不等于 2{
echo $z->getMessage();
}
catch (InvalidArgumentException $i) //如果参数类型不匹配{
echo $i->getMessage();
}
catch (Exception $ex) // 任何未捕获的异常{
echo $ex->getMessage();
}
?>
输出
首先,由于分母为 0,因此会显示"除以 0"错误
Division by 0
设置 $b=3,这将导致 TypeError,因为除法函数预期返回整数,但除法结果却是浮点数
Return value of divide() must be of the type integer, float returned
如果通过修改 $res=divide($a) 只向除法函数传递一个变量,这将导致 ArgumentCountError
Too few arguments to function divide(), 1 passed in C:\xampp\php\test1.php on line 13 and exactly 2 expected
如果其中一个参数不是整数,则会引发 InvalidArgumentException
Invalid type of arguments

