try catch自定义异常类的使用

 1 <?php
 2 //定义一个学生类
 3 class Student{
 4      //学生的名字
 5      private $name;
 6      //学生的年龄
 7      private $age;
 8 
 9   public function __construct($name,$age){
10 
11        $this->setName($name);
12        $this->setAge($age);
13   }
14   public function setName($name){
15         $this->name=$name;
16   }
17   public function setAge($age){
18         if(is_int($age)&&$age>18&&$age<25){
19          $this->age=$age;
20         }else{ 
21          //抛出一个异常并记录是哪个学生出错             
22          throw new StudentException($this,$this->name.'年龄出错',333);
23         }
24     }
25 
26 }
27 //自定义一个学生异常类,
28 //到时候清楚是哪个学生发生异常
29 class StudentException extends Exception{
30  
31     protected $student;
32 
33  //我们需要重写父类的构造方法
34  public function __construct($stu,$message,$code){
35 //记录下学生信息
36     $this->student=$stu;
37 
38   //上面的容易理解
39 //  $this->message=$message;
40 //  $this->code=$code;
41 
42 //问题有些疑惑关于这里
43 //我是这样理解代码的:重写父类的构造方法并没有得到父类值,这时候我们需要初始化父类的构造方法
44    parent::__construct($message,$code);
45  }
46  public function getStudent(){
47        
48        return $this->student;
49 
50      }
51 }
52 //监视所有的学生,如果有学生信息错误就返回相应信息
53 try{
54       $student1=new Student('aaa',21);
55       $student2=new Student('bbb',23);
56       $student3=new Student('ccc',19);
57       $student4=new Student('ddd',28);
58 
59 }
60 catch(StudentException $e){
61       echo "<pre>";
62       //获取发生错误学生的全部信息
63       var_dump($e->getStudent());
64       echo "发生的错误消息:".$e->getMessage();
65 }
66 ?>

 

转载于:https://www.cnblogs.com/ylmfg/p/5479638.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值