<?php
try
{
echo "比赛开始"."
";
throw new Exception('哇呀呀~运动员摔倒了'."
",40);
}
catch (Exception $e )
{
echo "获取错误信息:".$e->getMessage()."
";
echo "获取错误编码:".$e->getCode()."
";
}
echo "哎呀比赛结束了"."
";
?>
输出结果:
比赛开始
获取错误信息:哇呀呀~运动员摔倒了
- 自定义异常类
<?php
//自定义异常
class MyException extends Exception #自定义异常类继承自异常基类
{
public function demo()
{
echo "快把运动员扶起来";
}
}
try{
echo "比赛开始"."
";
throw new MyException("哎呀运动员摔倒了",40);
}
catch(MyException $e)
{
echo $e->getCode()."
";
echo $e->getMessage()."
";
echo $e->demo()."
";
}
echo "比赛结束"."
";
?>
输出结果:
比赛开始
40
哎呀运动员摔倒了
快把运动员扶起来
比赛结束
- 使用自定义myexception的重要原则
<?php
class myexception extends Exception { public function demo() { echo "快把运动员扶起来"." "; } } try{ echo "比赛开始"." "; throw new myexception('运动员被绊了一跤',20); #尽管抛出的是myexception,但是却被原生exception捕捉到了,所以自定义exception应该放在第一个! } catch (Exception $e) { echo $e->getMessage()." "; echo $e->getCode()." "; echo "上述是原生exception"." "; } catch ( myexception $e) { echo $e->getMessage()." "; echo $e->getCode()." "; echo $e->demo()." "; echo "上述是自定义myexception"." "; } ?>
输出结果:
比赛开始
运动员被绊了一跤
20
上述是原生exception
正确姿势: <?php
class myexception extends Exception { public function demo() { echo "快把运动员扶起来"." "; } } try{ echo "比赛开始"." "; throw new myexception('运动员被绊了一跤',20); } catch ( myexception $e) { echo $e->getMessage()." "; echo $e->getCode()." "; echo $e->demo()." "; echo "上述是自定义myexception"." "; } catch (Exception $e) { echo $e->getMessage()." "; echo $e->getCode()." "; echo "上述是原生exception"." "; } ?>
输出结果:
比赛开始
运动员被绊了一跤
20
快把运动员扶起来
上述是自定义myexception
- 特别函数set_exception_handler
<?php function heichouxianwaA($mywords) { echo $mywords->getMessage(); } set_exception_handler('heichouxianwaA'); throw new Exception("我满心欢喜打开我的未来"); ?>