/** PHP之异常转移 分析: 老师用电脑上课 问题领域涉及三个对象 学校 ,老师,电脑 ***/ //电脑异常 class ComputerLanPiException extends Exception { Public function __Construct($msg) { parent :: __Construct($msg); } } //电脑异常 class ComputerMaoYanException extends Exception { Public function __Construct($msg) { parent :: __Construct($msg); } } /***学校问题主要管理学校的课程进度的问题异常**/ class NoPlanException extends Exception { Public function __Construct($msg) { parent :: __Construct($msg); } } Class Computer { private $state = 2; //电脑 状态 Public function run() { //若是是java的话那么 他会对run函数进行总体抛出 throw xx ,xx if($this->state == 1) { throw new ComputerLanPiException('电脑蓝屏了'); } if($this->state ==2) { throw new ComputerMaoYanException('电脑冒烟了'); } echo '电脑运行了...<br/>'; } //重启电脑 Public function reset() { echo '电脑重启了<br/>'; $this->state = 0 ; } } Class Teacher { Private $names; //老师的名字 Private $comp; //老师的电脑 Public function __Construct($name,$comp) { $this->names = $name; $this->comp = $comp; } Public function Prelect () { try{ $this->comp->run(); //先运行电脑 echo $this->names.'讲课者'; //老师名字 } catch (ComputerLanPiException $e) { //若是出现蓝屏的异常咱们就直接重启 $this->comp->reset(); //重启 $this->Prelect() ; //开始讲课对吧 echo '<hr/>'; echo $e->__toString(); //把对象转换为字符串 } catch (ComputerMaoYanException $e){ //电脑坏了怎么办法 echo '电脑冒烟了..<br/>'; $this->test(); /****************异常转移*********************/ //echo '<hr/>'; //异常转换 //throw $e; //继续向上抛出异常 这样抛不合理 由于 学习这块也没办法去解决这状况电脑换了的状况 //echo $e->__toString(); //把对象转换为字符串 //java中直接 throw e; //throw new ComputerMaoYanException('电脑冒烟了'); //继续抛出异常 $msg ='课程没法完成 缘由:'.$e->__toString(); //把对象转换成字符串 //异常转换 throw new NoPlanException ($msg); //抛出课程进度没法完成的异常//这叫异常转换 /****************异常转移*********************/ } } Private function test() { echo '作你们练习'; } } class ExceptionsTest { /**自定义主函数*/ Public Static function Main(){ $comp = new Computer(); $t = new Teacher("任老师",$comp); //初始化老师 try{ $t->Prelect(); //调用老师讲课 } catch(NoPlanException $e) { //这叫异常转换 echo '<hr/>'; echo $e->getMessage(); echo '<hr/>'; echo ' 学校立刻换人了....'; /***下面就是换人的****/ $comp = new Computer(); $comp->reset(); $t = new Teacher("王老师",$comp); //初始化老师 $t->Prelect(); //调用老师讲课 } } } header("Content-Type:text/html;charset=utf-8;"); ExceptionsTest :: Main(); //入口