我们在开发中会使用到各种的类库,各种各样的类库,可能是传递参数等问题,发生异常,难免会出现错误,自动把错误提交过来
<?php
class Code{
public function make($len){
$this->line($len);
}
public function line(int $len){
if($num > 5){
return false;
}
}
}
class Code{
protected $error;
public function make(int $len){
if($this->line($len) === false){
return false;
}
}
public function line(int $len){
if($len > 5){
$this->error = "验证码数量不能超过5个";
return false;
}
}
public function error(){
return $this->error;
}
}
include "Code.php";
$code = new Code();
//echo "fewew";
//var_dump($code->make(50));
if($code->make(50) === false){
echo $code->error();
}
那这样的的错误处理就非常的麻烦
有很多的判断
<?php
class Code{
// protected $error;
public function make(int $len){
$this->line($len);
// if($this->line($len) === false){
// return false;
// }
}
public function line(int $len){
if($len > 5){
//$this->error = "验证码数量不能超过5个";
//return false;
throw new Exception("验证码数量不能超过5个");
}
}
// public function error(){
// return $this->error;
// }
}
?>
try {
//code...
$code = new Code;
$code->make(100);
} catch (Exception $e) {
echo $e->getMessage();
}
多个异常类的使用
登录的时候,有自己的异常类,登录失败的时候有自己的异常类
用户发文章的时候,也会有专门的异常类进行处理
class LoginException extends Exception{
}
class UploaderException extends Excetpion{}
try{
throw new LoginException("您还没有登录",403);
throw new UploaderException("您还没有登录",403);
}catch(LoginException $e){
echo 333;
}catch(UploaderException $e){
echo 555;
}finally{
echo "永远执行";
}
无论抛不抛异常,finally中的代码都会执行
通过不同的业务,自定义不同的异常,这样别人在用你的异常时,就会变得非常的简单
如果使用了系统异常类Exception,要把它放到最后面,有一个优先级的问题,Exception可以处理所有继承于它的异常类
try{
}catch(LoginException $e){}
catch(Excetpion $e){}
$e->getFile();//得到错误的文件
$e->getCode();//得到错误的代码
$e->getLine();//得到错误的行号
$e->getMessage();//得到错误的消息
echo $e;//魔术方法,__toString();
getFile()是final类,不能被重写
重写的异常类可以自定义__toString()魔术方法
t
h
i
s
−
>
g
e
t
F
i
l
e
(
)
.
this->getFile().
this−>getFile().this=>getLine();
显示错误问题
__toString()用于把对象转化为字符串输出时来使用
可以使用其他方法,比如用户登录次数等等