如果你对该文章中的内容有疑问/不解,可以点击此处链接提问
要注明问题和此文章链接地址 点击此处跳转
try{}catch(){}
1 2 3 4 5 |
try{ 要测试的语句,带有(抛出一个错误对象)throw new Exception('出错啦',100); }catch(Exception $a){ $a->getMessage(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class A { private $age='200'; public function show () { if($this->age > 150 || $this->age < 0 ){ throw new Exception('年龄错误'); } } } try{ $a = new A; $a->show(); }catch(Exception $a){ echo $a->getMessage(); } |
异常信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class A { private $a=0; public function show() { if($this->a == 0){ throw new Exception('不能为0',100);//编号 } } } try{ $a = new A; $a->show(); }catch(Exception $a){ echo $a->getMessage();//异常消息 echo $a->getCode();//异常编号(编号可自定义) echo $a->getFile();//异常文件 E:\WWW\lianxi\0104\5.php echo $a->getLine();//异常行数 var_dump($a->getPrevious());//NULL var_dump($a->getTrace());//以数组的形式展示具体内容 //array(1) { [0]=> array(6) { ["file"]=> string(24) "E:\WWW\lianxi\0104\5.php" ["line"]=> int(30) ["function"]=> string(4) "show" ["class"]=> string(1) "A" ["type"]=> string(2) "->" ["args"]=> array(0) { } } } var_dump($a->getTraceAsString()); //string(52) "#0 E:\WWW\lianxi\0104\5.php(30): A->show() #1 {main}" } |
自动接收异常set_exception_handler()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function autoException(Exception $a){ echo $a->getMessage(); } set_exception_handler('autoException');//函数名,,,带引号//// function s($a,$b) { if($b == 0){ throw new Exception('除数不能为0'); } return $a/$b; } s(10,0); |