php抛出异常Exception和\Exception使用区别

php抛出异常Exception和\Exception使用区别

没有定义命名空间的情况下 , Exception和\Exception 均可正常执行抛出异常;
定义命名空间的情况 , Exception 会在定义的命名空间下找对应的异常类 , 如果没有定义异常类 , 则会报错 ;
定义命名空间的情况 , \Exception 会按照php默认的异常类执行抛出异常 ;

建议:  抛出异常 使用 \Exception !


 

#1: 没有定义命名空间 使用Exception

<?php
try {
  throw new Exception("抛出异常");
} catch (Exception $e) {
  echo '捕获到异常'.$e->getMessage();
}
 

#1> 执行结果
捕获到异常抛出异常


 

 

#2: 没有定义命名空间 使用\Exception

<?php
try {
  throw new \Exception("抛出异常");
} catch (\Exception $e) {
  echo '捕获到异常'.$e->getMessage();
}
 

#2> 执行结果
捕获到异常抛出异常


 

 

#3: 有定义命名空间 使用Exception

<?php
namespace Test;

try {
  throw new Exception("抛出异常");
} catch (Exception $e) {
  echo '捕获到异常'.$e->getMessage();
}
 

#3> 执行结果
Fatal error: Uncaught Error: Class 'Anxiaojing\Exception' not found *** Stack trace: #0 {main} thrown in ***

 

#4>: 有定义命名空间 使用\Exception

<?php
namespace Test;

try {
  throw new \Exception("抛出异常");
} catch (\Exception $e) {
  echo '捕获到异常'.$e->getMessage();
}
#4> 执行结果
捕获到异常抛出异常
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值