为什么我的PHP异常不起作用?

时间:2016-03-19 02:20:47

标签: php exception-handling

我不熟悉PHP中的异常或任何语言。如果用户输入无效的文本时区(在本例中为“xxxxxxxxxx”),我试图捕获异常。我的测试用例肯定是无效的,因为触发了异常,而不是智能处理它的catch逻辑。基本上我希望它在使用无效的时区时使用有效的时区字符串。

echo $tz_text . '~' . $username . '<br />';
try
{
    $tz = new \DateTimeZone($tz_text);
}
catch (Exception $e)
{
    // Handles the issue of a timezone not being correct, see http://php.net/manual/en/timezones.php
    if ($this->config['phpbbservices_digests_enable_log'])
    {
        $this->phpbb_log->add('admin', $this->user->data['user_id'], $this->user->ip, 'LOG_CONFIG_DIGESTS_TIMEZONE_ERROR', array($tz_text, $username, $this->config['board_timezone']));
    }
    $tz = new \DateTimeZone($this->config['board_timezone']);
}

我回来了:

xxxxxxxxxx~Mark D Hamill

致命错误:消息'DateTimeZone :: __ construct()的未捕获异常'异常':/ Applications / XAMPP / xamppfiles / apps / phpbb / htdocs / ext / phpbbservices / digests / cron中的未知或错误时区(xxxxxxxxxx) /task/digests.php:1938堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(1938):DateTimeZone-&gt; __ construct(' xxxxxxxxxx')#1 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(514):phpbbservices \ digests \ cron \ task \ digests-&gt; make_tz_offset(' xxxxxxxxxx','Mark D Hamill')#2 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(157):phpbbservices \ digests \ cron \ task \摘要 - &gt; mail_digests(1458353337,0)#3 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/acp/main_module.php(1427):phpbbservices \ digests \ cron \ task \ digests-&gt ; run()#4 / Applications / XAMPP / xamppfiles / apps / phpbb / htdocs / includes / functions_modu le.php(674):phpbbservices \ digests \ acp \ main_module-&gt;在1938行的/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php中

第1938行是应该捕获错误的地方:

    $tz = new \DateTimeZone($tz_text);

1 个答案:

答案 0 :(得分:1)

看起来上面的代码片段在命名空间内。请考虑以下代码 -

<?php

namespace Foo/Bar;

try {
   ...
} catch (Exception $e) { // This is trying to catch Foo/Bar/Exception
   ...
}

通过将代码更改为此类来明确指定它的解决方案 -

try {
    ....
} catch (\Exception $e) {
    ....
}

进一步阅读 - http://php.net/manual/en/language.namespaces.php http://php.net/manual/en/language.namespaces.basics.php

的Rahul