1.2.894. Overwritten Exceptions

In catch blocks, it is good practice to avoid overwriting the incoming exception, as information about the exception will be lost.

<?php

try {
    doSomething();
} catch (SomeException $e) {
    // $e is overwritten
    $e = new anotherException($e->getMessage());
    throw $e;
} catch (SomeOtherException $e) {
    // $e is chained with the next exception
    $e = new Exception($e->getMessage(), 0, $e);
    throw $e;
}

?>

1.2.894.1. Suggestions

  • Use another variable name to create new values inside the catch

  • Use anonymous catch clause (no variable caught) in PHP 8.0, to make this explicit

1.2.894.2. Specs

Short name

Exceptions/OverwriteException

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior, Suggestions

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

exception

Available in

Entreprise Edition, Community Edition, Exakat Cloud