具有多个catch块的PHP异常处理
介绍
PHP允许在try块之后的一系列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,因为除法函数应返回整数,但除法会导致浮点数
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