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


Why isn't my PHP exception working?

我真的是PHP或任何语言的异常新手。如果用户输入无效的文本时区(在本例中为"xxxx"),我正在尝试捕获异常。我的测试用例绝对无效,因为触发了异常,只是不是应该智能处理它的捕获逻辑。基本上,如果输入了无效的时区字符串,我希望它使用有效的时区字符串。

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']);
}

我回来了:

xxx~马克·哈米尔

致命错误:未捕获的异常"异常",消息为"日期时区::__construct():未知或错误的时区 (xxxx)"在/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php:1938 堆栈跟踪:#0/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests

.php(1938): DateTimeZone->__construct('xxxxx') #1/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(514): phpbbservices''digests''cron''task''digests->make_tz_offset('xxxxxx', 'Mark D Hamill') #2/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(157): phpbbservices''digests''cron''task''digests->mail_digests(1458353337, 0) #3/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/acp/main_module.php(1427): phpbbservices''digests''cron''task''digests->run() #4/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/include/functions_module.php(674): phpbbservices''digests''acp''main_module-> in/Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php on line 1938

第 1938 行是应捕获错误的位置:

    $tz = new 'DateTimeZone($tz_text);

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

<?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