PHP中的try/catch块未捕获异常 [英] Try/Catch block in PHP not catching Exception

查看:603
本文介绍了PHP中的try/catch块未捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从此页面运行此示例#1: http://php .net/manual/en/language.exceptions.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) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>

但是我得到的不是期望的输出:

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

我正在使用的开发人员环境是UniServer 3.5PHP 5.2.3

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

推荐答案

我只是遇到了一个确切的问题,似乎我什至已经复制了异常的名称,但没有捕获到它.原来这是我的愚蠢错误,但我认为如果其他人也遇到同样的情况,我应该在此发布我的案子.

I just had this exact problem where it seemed like I had even copied the name of the exception and yet it didn't catch it. It turned out it was my stupid mistake but I thought I should post my case here in case there is someone else in the same situation.

我在名为 A 的命名空间中遇到了例外,脚本在名为 B 的命名空间中.问题是我有 A \ MyException 等于(在PHP中) \ B \ A \ MyException (因为我的脚本位于名为 B !).我要解决的所有事情就是在异常名称中添加反斜杠(或其他名称),使其看起来像这样: \ A \ MyException

I had my exception in my namespace called A and the script was in a namespace called B. The problem was that I had A\MyException which equals (in PHP) \B\A\MyException (because my script is in the namespace called B!). All I had to do to fix it was to add backslash (or whatever it's called) to the exception name so it would look like this: \A\MyException

这篇关于PHP中的try/catch块未捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆