Exception Must Be Thrown

ID

php.exception_must_be_thrown

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

exception-handling, reliability

Description

Reports a new SomeException(…​) (or …​Error) expression that is created as a bare statement and never thrown. The exception object is allocated and then immediately discarded, so the error condition it was meant to signal silently disappears.

Rationale

Constructing an exception has no effect on control flow on its own — only throw raises it. A line such as new RuntimeException('bad state'); reads as if it aborts the operation, but execution simply continues to the next statement. This is almost always a forgotten throw keyword, leaving the program running in the very state the exception was supposed to prevent. Exceptions that are returned, assigned, or passed as arguments are left alone, since the receiving code may raise them later.

<?php
function process(int $qty): void
{
    if ($qty < 0) {
        new InvalidArgumentException('negative quantity'); // FLAW — created but never thrown
    }

    if ($qty === 0) {
        throw new LogicException('empty order');           // OK — actually thrown
    }

    $error = new RuntimeException('stored for later');     // OK — assigned, may be thrown later
}

Remediation

Add the missing throw keyword so the exception interrupts execution (throw new InvalidArgumentException('negative quantity');). If the construction was genuinely intended only to build an object for later use, assign or return it so the intent is explicit.