带有多个 catch 块的 PHP 异常处理
简介
PHP 允许在 try 块后面使用一系列 catch 块来处理不同的异常情况。各种 catch 块可用于处理预定义的异常和错误,以及用户定义的异常。
示例
以下示例使用 catch 块来处理 DivisioByZeroError、TypeError、ArgumentCountError 和 InvalidArgumentException 条件。还有一个 catch 块用于处理一般的 Exception 情况。
示例
<?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)//if argument types not matching{
echo $x->getMessage();
}
catch (DivisionByZeroError $y) //if denominator is 0{
echo $y->getMessage();
}
catch (ArgumentCountError $z) //if no.of arguments not equal to 2{
echo $z->getMessage();
}
catch (InvalidArgumentException $i) //if argument types not matching{
echo $i->getMessage();
}
catch (Exception $ex) // any uncaught exception{
echo $ex->getMessage();
}
?>输出
首先,由于分母为 0,因此会显示除以 0 错误
Division by 0
将 $b 设置为 3,这将导致 TypeError,因为 divide 函数预期返回整数,但除法结果为浮点数
Return value of divide() must be of the type integer, float returned
如果通过更改 $res=divide($a); 只向 divide 函数传递一个变量,这将导致 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP