'Why isn't my PHP exception working?

I am new to exceptions in PHP or any language really. I am trying to catch an exception if a user enters an invalid textual timezone ("xxxxxxxxxx" in this case). My test case is definitely invalid as an exception is triggered, just not the catch logic which is supposed to handle it intelligently. Basically I want it to use a valid timezone string if an invalid one is entered.

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

I get back:

xxxxxxxxxx~Mark D Hamill

Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone (xxxxxxxxxx)' in /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php:1938 Stack trace: #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-> in /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php on line 1938

Line 1938 is where the error should be caught:

    $tz = new \DateTimeZone($tz_text);


Solution 1:[1]

It looks like the code snippet above is inside a namespace. Consider the following code:

<?php

namespace Foo\Bar;

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

The solution to this is to explicitly specify it by changing your code to be something like this:

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

Further reading:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Angel Politis