1.2.120. Catch With Undefined Variable

Always initialize every variable before the try block, when they are used in a catch block. If the exception is raised before the variable is defined, the catch block may have to handle an undefined variable, leading to more chaos.

<?php
     $a = 1;
     try {
         mayThrowAnException();
         $b = 2;
     } catch (\Exception $e) {
         // $a is already defined, as it was done before the try block
         // $b may not be defined, as it was initialized after the exception-throwing expression
         echo $a + $b;
     }
?>

See also catch and Non-capturing exception catches in PHP 8.

1.2.120.1. Suggestions

  • Always define the variable used in the catch clause, before the try block.

1.2.120.2. Specs

Short name

Exceptions/CatchUndefinedVariable

Rulesets

All, Analyze, Changed Behavior

Exakat since

2.1.5

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud