php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #80389 With strict_types=1 catch type not validated
Submitted: 2020-11-20 16:43 UTC Modified: 2020-11-20 16:55 UTC
From: tom at tomegan dot tech Assigned:
Status: Not a bug Package: *Programming Data Structures
PHP Version: 7.4.12 OS: any
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: tom at tomegan dot tech
New email:
PHP Version: OS:

 

 [2020-11-20 16:43 UTC] 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

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-11-20 16:55 UTC] danack@php.net
-Status: Open +Status: Not a bug
 [2020-11-20 16:55 UTC] danack@php.net
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.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 21:01:30 2024 UTC