【笔记】异常处理
admin
2023-07-05 04:22:46
0次
异常处理抛出和捕获异常try 功能检查异常catch 捕获异常throw 抛出异常try{ ... throw new Exception($errmsg,$errcode)}catch(Exception $e){ ...}try之后至少要有一个catch,成对出现基本异常类Exception1.接受两个参数 错误信息和错误代码2.内置方法 getMessage 返回传递给构造函数的方法 getCode 返回传递给构造函数的代码 getFile 返回发生异常的代码文件路径 getLine 返回代码行号 __tostring 输出所有异常信息3.扩展基本异常类 继承Exception
try {
$num = 0;
if($num == 0){
$errmsg = "除数不能为0";
throw new newException($num);
}else {
echo 500/$num;
}
} catch (newException $e) {
$e->errMessage();
}
class newException extends Exception{
function errMessage(){
echo "错误信息:"."除数".$this->getMessage()."不能为零
";
echo "错误文件:".$this->getFile()."
";
echo "错误行:".$this->getLine();
}
}
?>
4.捕获多个异常
使用if和else或者swith
捕获异常是往往仍然需要捕获Exception类,来处理捕获的异常
从上往下的顺序,如果先捕获Exception类导致不能被正确的代码执行,特定的异常写在前面,一般异常的catch写在后面
示例:
class customException extends Exception{
public function errMessage(){
$errMsg = "错误信息:".$this->getMessage()."
";
$errMsg.="错误文件路径:".$this->getFile()."
";
$errMsg.="错误代码行号:".$this->getLine();
return $errMsg;
}
}
$email = "sunyan@example.....com";
try {
if(filter_var($email,FILTER_VALIDATE_EMAIL)==FALSE){
throw new customException("".$email."错误的邮箱地址");
}
if(strpos($email,"example")!=FALSE){
throw new customException("".$email."是一个example电子邮件地址");
}
}catch (customException $e){
echo $e->errMessage();
}
catch (Exception $e) {
echo $e->getMessage();
}
相关内容