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): phpbbservicesdigestscrontaskdigests->make_tz_offset(‘xxxxxxxxxx’, ‘Mark D Hamill’) #2 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/cron/task/digests.php(157): phpbbservicesdigestscrontaskdigests->mail_digests(1458353337, 0) #3 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/ext/phpbbservices/digests/acp/main_module.php(1427): phpbbservicesdigestscrontaskdigests->run() #4 /Applications/XAMPP/xamppfiles/apps/phpbb/htdocs/includes/functions_module.php(674): phpbbservicesdigestsacpmain_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);
Advertisement
Answer
It looks like the code snippet above is inside a namespace. Consider the following code:
<?php namespace FooBar; 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: