Catch Variable Reassigned

ID

php.catch_variable_reassigned

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

Php

Tags

error-handling, reliability

Description

Reports an assignment inside a catch block whose target is the caught exception variable itself, for example $e = new LogicException('x');.

Rationale

Overwriting the catch variable throws away the original exception object — and with it the stack trace and context that explain what actually went wrong. Any later code in the block that reads the variable now sees the replacement, and the exception chain is broken. If a new exception needs to be raised, build it in a fresh local and pass the original as the previous exception so the chain is preserved.

<?php
try {
    $this->step();
} catch (\RuntimeException $e) {
    $e = new \LogicException('wrapped');           // FLAW — original exception discarded
    throw $e;
}

try {
    $this->step();
} catch (\RuntimeException $e) {
    throw new \LogicException('wrapped', 0, $e);   // OK — original kept as previous
}

Remediation

Do not assign to the catch variable. Read what you need from it, and when raising a new exception construct it separately, forwarding the caught exception as the third constructor argument (new LogicException($message, $code, $e)) to keep the full exception chain.