Req #80389 [Opn->Nab]: With strict_types=1 catch type not validated
| From: | danack@php.net | Date: | Fri, 20 Nov 2020 16:55:05 +0000 |
| Subject: | Req #80389 [Opn->Nab]: With strict_types=1 catch type not validated | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-230483@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=80389&edit=1
ID: 80389
Updated by: danack@php.net
Reported by: tom at tomegan dot tech
Summary: With strict_types=1 catch type not validated
-Status: Open
+Status: Not a bug
Type: Feature/Change Request
Package: *Programming Data Structures
Operating System: any
PHP Version: 7.4.12
Block user comment: N
Private report: N
New Comment:
PHP doesn't validate class names in exceptions. And doesn't try to validate/load classes
when you refer to their name.
PHP can check that 'Bug\Exception' is not any of the parent classes of Exception, without
loading it, so it doesn't.
Previous Comments:
------------------------------------------------------------------------
[2020-11-20 16:43:20] tom at tomegan dot tech
Description:
------------
I encountered an issue with code in a namespaced file and strict_types=1 where i forgot to include
either a use statement for \Exception or indicate I wanted to catch an Exception in the default
namespace. I expected this code to trigger a warning or raise a TypeError as the implied type did
not exist. However, it appears that the type in a catch statement is not validated. In my example,
the catch statement tries to catch a Bug\Exception, however this class does not exist and does not
match the \Exception which is thrown. The thrown \Exception is therefore reported back. I believe
that PHP developers would benefit from PHP adding validation of the type to the catch statement at
least in some configuration(s) eg strict_types=1
Test script:
---------------
<?php
/**
* The type in a catch statement is not validated even with strict_type=1
*
* @author Tom Egan
*/
declare(strict_types=1);
namespace Bug;
try {
throw new \Exception('A test exception');
} catch(Exception $e) {
echo $e->getMessage();
}
exit;
Expected result:
----------------
$ php bug-test.php
PHP Fatal error: Uncaught TypeError: the type Bug\Exception does not exist bug-test.php:15
Stack trace:
#0 {main}
thrown in bug-test.php on line 15
Actual result:
--------------
$ php bug-test.php
PHP Fatal error: Uncaught Exception: A test exception in bug-test.php:14
Stack trace:
#0 {main}
thrown in bug-test.php on line 14
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=80389&edit=1