php / php/doc-en

Exception thrown in catch is caugh silently when finally has return statement

Open
#1,870 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug Status: Needs Triage
Dominant language
XML
Stars
596
Forks
890
Avg merge
1d 15h
Merged PRs (30d)
55

Description

Description

The following code:

<?php 

define('DO_RETURN', true);

function execute() {
    try {
        throw new \Exception('root exception'); // throws exception
    } catch (\Throwable $e) {
        echo "[catch]"; // exception is handled somehow 
        throw $e; // and rethrown
        return; // never called
    } finally {
        echo "[finally]"; // finally is handed
        if (DO_RETURN)
            return; // if return is here the thrown exception is ignored and silently scratched
    }
}

execute(); // the exception was rethrown, so should be thrown after finally

Resulted in this output:

[catch][finally]

But I expected this output instead:

[catch][finally]
Fatal error: Uncaught Exception: root exception in /in/aLqm4:7
Stack trace:
#0 /in/aLqm4(19): execute()
php/php-src#1 {main}
  thrown in /in/aLqm4 on line 7

Process exited with code 255.

https://3v4l.org/aLqm4

I understand that it happens because

Additionally, if the finally block also contains a return statement, the value from the finally block is returned.
-- https://www.php.net/manual/en/language.exceptions.php#language.exceptions.finally

But I don't think it should be possible to silently catch an exception outside of catch statement.

PHP Version

7.4.0 - 7.4.32, 8.0.1 - 8.0.24, 8.1.0 - 8.1.11, 8.2rc1 - rc3

Operating System

any OS

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the PHP manual's linked finally section and compare its explanation with the issue's try/catch/finally example. Clarify the documented behavior when finally contains return and suppresses a rethrown exception, using the reported output to verify that the explanation matches the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.