exception测试

1. 存在多个set_error_handle 或 set_exception_handle 的时候,会如何处理?

 <?php
 function inverse($x) {
   if (!$x) {
       throw new Exception('Division by zero.');
    }
    return 1/$x;
 }
 function onException1($e){
     echo "exception1\n";
     echo $e->getMessage();
 }
 function onException2($e){
         echo "lxx_exception2\n";
         echo $e->getMessage();
    }
 
 set_exception_handler("onException1");
 set_exception_handler("onException2");
 
 try {
    echo inverse(0) . "\n";
 } catch (Exception $e) {
     echo 'Caught exception: ',  $e->getMessage(), "\n";
 }
echo inverse(0) . "\n";

// Continue execution
//require("laruence.php")

上面代码的执行结果:

Caught exception: Division by zero.
exception2
Division by zero.

从执行结果可以发现:
(1)当存在多个set_exception_handler时,只执行最后一个
(2)try catch内的不会被set_exception_handler捕捉到

2.set_exception_handle 添加日志?

在set_exception_handle定义的exception函数中可以进行更灵活的日志记录,在打印exception信息的同时能够带上自定义的日志信息

3.@还能不能抑制住exception?

可以:

  1 <?php
  2 function inverse($x) {
  3     if (!$x) {
  4         throw new Exception('Division by zero.');
  5     }
  6     return 1/$x;
  7 }
  8 function onException1($e){
  9     echo "Caught exception1\n" . $e->getMessage();
 10     echo "\n";
 11 }
 12 function onException2($e){
 13         echo "Caught exception2\n" .$e->getMessage();
 14         echo "\n";
 15    }
 16 
 17 set_exception_handler("onException1");
 18 set_exception_handler("onException2");
 19 //$a = @inverse(0);
 20 $file = fopen('a.txt', 'r');
 21 
 22 try {
 23     $file =@fopen('a.txt', 'r');
 24 } catch (Exception $e) {
 25     echo 'Caught exception: ',  $e->getMessage(), "\n";
 26 }
 27 
 28 // Continue execution
 29 //require("laruence.php")
 30 ?>

第20行:fopen(‘a.txt’, ‘r’);加@前结果:

PHP Warning:  fopen(a.txt): failed to open stream: No such file or directory in /root/test_php/test_exception.php on line 20
PHP Stack trace:
PHP   1. {main}() /root/test_php/test_exception.php:0
PHP   2. fopen() /root/test_php/test_exception.php:20

第二十行:fopen(‘a.txt’, ‘r’);加@后不输出任何内容,表明@可以抑制住;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值