【问题标题】:Why isn't my PHP exception working?为什么我的 PHP 异常不起作用?
【发布时间】:2016-03-19 02:20:46
【问题描述】:

我真的是 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~马克·D·哈米尔

致命错误:在 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron 中带有消息“DateTimeZone::__construct(): Unknown or bad timezone (xxxxxxxxxx)”的未捕获异常“Exception” /task/digests.php:1938 堆栈跟踪:#0 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(1938): DateTimeZone->__construct('xxxxxxxxxx ') #1 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(514): phpbbservices\digests\cron\task\digests->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\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/includes/functions_module.php(674): phpbbservices\digests\acp\main_module-> 在 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php 1938 行

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

    $tz = new \DateTimeZone($tz_text);

【问题讨论】:

    标签: php exception-handling


    【解决方案1】:

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

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

    拉胡尔

    【讨论】:

    • 谢谢。盯着我的脸,就像很多这样的问题!
    猜你喜欢
    • 2020-01-19
    • 1970-01-01
    • 2013-12-28
    • 2023-02-06
    • 2018-05-14
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    相关资源
    最近更新 更多