Re: [RFC] Context Managers
| From: | Rob Landers | Date: | Thu, 30 Apr 2026 07:42:24 +0000 |
| Subject: | Re: [RFC] Context Managers | ||
| References: | 1 2 3 4 5 6 7 8 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-130712@lists.php.net to get a copy of this message | ||
On Wed, Apr 29, 2026, at 17:04, Larry Garfield wrote:
> On Wed, Apr 29, 2026, at 9:30 AM, Rob Landers wrote:
> > On Wed, Apr 22, 2026, at 20:28, Larry Garfield wrote:
> >> I think a key question to answer here is: Do we care to differentiate between CM
> >> errors and underlying errors?
> >
> > I don't think we need to differentiate at the CM level. Suppression is
> > a policy decision that belongs to the caller, not the context manager.
> > The CM's job is cleanup: rollback the transaction, close the file,
> > release the lock, etc. Whether the exception continues propagating
> > after that is the caller's call, and
try using
> > already provides
> > exactly that:
> >
> > try using ($db->transaction() => $conn) {
> > $conn->execute('INSERT INTO orders ...');
> > } catch (ValidationException $e) {
> > // Caller chooses to suppress this here
> > }
> >
> > That makes exitContext() simple: return void, do your
> > cleanup, and
> > get out. If cleanup fails, it throws naturally, and the desugared form
> > can chain the original exception as $previous so the root
> > cause isn't
> > lost. If the caller wants to suppress or differentiate, they already
> > have try using for exactly that.
> >
> > It's worth noting that every example in the RFC (database transactions,
> > file locks, error handler swaps, async scopes) does cleanup and
> > propagates. None of them actually need the power to suppress. If a
> > context manager wants to give callers a clean exception hierarchy to
> > catch against, it can wrap underlying exceptions in their own types
> > during cleanup. That's just normal exception design, no special syntax
> > required.
> >
> > — Rob
>
> Just to make sure I'm following you, you're arguing that a CM should not have any way
> at all to suppress an exception? I don't think I'd agree with that, personally. Even if
> it's a rare case, I do believe it's a feature that should remain.
I'd argue CMs are mechanisms, not policies. They encode setup and teardown. Suppression is an
error-handling policy decision that should be visible at the call site, not mixed with the concerns
of setting up and tearing down resources.
If CM's could suppress arbitrary exceptions, from a developer stepping over the code,
they'd see the code randomly appear to jump out of the using block after a suppressed exception
... at seemingly arbitrary points. There would be no way to trust what you were reading without
having the CM's code in front of you as well.
— Rob