dongteng0748 2010-01-31 18:09
浏览 67

在PHP中尝试/捕获块不捕获异常

I am trying to run this Example #1 from this page: http://php.net/manual/en/language.exceptions.php

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}
try {
    echo inverse(5) . "
";
    echo inverse(0) . "
";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "
";
}
// Continue execution
echo "Hello World
";
?>

However instead of the desired output I get:

0.2
Fatal error: Uncaught exception 'Exception' with message 'Division by zero.' 
in xxx:
7 Stack trace: #0 xxx(14): inverse(0) #1 {main} thrown in xxx on line 7

The developer environment I am using is UniServer 3.5 with PHP 5.2.3

  • 写回答

9条回答 默认 最新

  • dpkrh2444 2010-01-31 23:11
    关注

    My initial though is you have a typo in the name of the exception you are catching/throwing, but if your code is exactly the same I'm not sure exactly what is going on.

    Try the following modification of the original script, and paste your results. It will help diagnose your issue a bit better.

    <?php
    
    //set up exception handler to report what we didn't catch
    function exception_handler($exception) {
    
        if($exception instanceof MyException) {
            echo "you didn't catch a myexception instance
    ";
    
        } else if($exception instanceof Exception) {
            echo "you didn't catch a exception instance
    ";
    
        } else {
            echo "uncaught exception of type: ".gettype($exception)."
    ";
        }
    
        echo "Uncaught exception: " , $exception->getMessage(), "
    ";
    }
    
    //install the handler
    set_exception_handler('exception_handler');
    
    class MyException extends Exception {
    }
    
    function inverse($x) {
        if (!$x) {
            throw new MyException('Division by zero.');
        }
        else return 1/$x;
    }
    
    try {
        echo inverse(5) . "
    ";
        echo inverse(0) . "
    ";
    } catch (MyException $e) {
        echo 'Caught myexception: ',  $e->getMessage(), "
    ";
    } catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "
    ";
    }
    
    // Continue execution
    echo 'Hello World';
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么