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
 [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-2021 The PHP Group
All rights reserved.
Last updated: Wed Oct 20 14:03:39 2021 UTC