1.2.1189. Throw In Destruct

According to the manual, Attempting to throw an `exception <https://www.php.net/exception>`_ from a destructor (called in the time of script termination) causes a fatal `error <https://www.php.net/error>`_.

The destructor may be called during the lifespan of the script, but it is not certain. If the exception is thrown later, the script may end up with a fatal error.

Thus, it is recommended to avoid throwing exceptions within the __destruct method of a class.

<?php

// No exception thrown
class Bar {
    function __construct() {
        throw new Exception('__construct');
    }

    function __destruct() {
        $this->cleanObject();
    }
}

// Potential crash
class Foo {
    function __destruct() {
        throw new Exception('__destruct');
    }
}

?>

See also Constructors and Destructors.

1.2.1189.1. Suggestions

  • Remove any exception thrown from a destructor

1.2.1189.2. Specs

Short name

Classes/ThrowInDestruct

Rulesets

All, Analyze, CE, CI-checks, PHP recommendations

Exakat since

0.8.4

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Very high

Features

throw

Available in

Entreprise Edition, Community Edition, Exakat Cloud