PHP抛出异常
介绍
Throwable接口由Error和Exception类实现。所有预定义的错误类均继承自错误类。相应的Error类的实例被抛出在try块中,并在适当的catch块中进行处理。
投掷错误
在顺序定义的最后一个catch块之后,正常执行(当try块内没有引发异常时)将继续。
示例
<?php
function div($x, $y) {
if (!$y) {
throw new Exception('Division by zero.');
}
return $x/$y;
}
try {
echo div(10,5) . "\n";
echo div(10,0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
//继续执行
echo "Execution continues\n";
?>输出结果
显示以下输出
2 Caught exception: Division by zero. Execution continues
在下面的示例中,执行函数时会抛出TypeError,因为没有将适当的参数传递给它。显示相应的错误信息
示例
<?php
function add(int $num1, int $num2){
return $num1 + $num2;
}
try {
$value = add(1, 'one');
} catch (TypeError $e) {
echo $e->getMessage(). "\n";
}
?>输出结果
显示以下输出
Argument 2 passed to add() must be of the type integer, string given
SPL例外
标准PHP库包含预定义的异常
下面的示例显示未在PHP数组中找到键时引发的OutOfBoundsException
示例
<?php
$arr=array("one"=>1, "two"=>2,"three"=>3,"four"=>4);
$key="ten";
try{
if (array_key_exists($key, $arr)==FALSE){
throw new OutOfBoundsException("key not found");}
else {
echo $arr[$key];}
}
catch (OutOfBoundsException $e){
echo $e->getMessage(). "\n";
}
?>输出结果
显示以下输出
key not found