hvertous
hvertous

Reputation: 1173

Throwing an exception in destructor method

I cannot find a reliable source to ensure that I am able to throw an exception inside __destruct().

This is what php documentation says

Attempting to throw an exception from a destructor (called in the time of script termination) causes a fatal error.

But when I test it

class A 
{
    public function __destruct()
    {
       throw new \Exception();
    }
}

try {
    $a = new A();

} catch(\Exception $x) {
    var_dump($x);
}

it seems that this is not true. I throw and catch exceptions normally. So, why has the doc got this line?

edited after Mark Baker's answer:

it actually works, the exception can be thrown and caught from destructor. I am still uncertain why the documentation lies then.

Upvotes: 3

Views: 1192

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

The destructor isn't being called anywhere in your script, so your try/catch block won't catch anything. If you unset($x) inside the try/catch block, then an exception will be thrown, and duly caught.

class A {
    public function __destruct() {
       throw new \Exception();
    }
}

try {
    $a = new A();
    unset($a);
} catch(\Exception $x) {
    var_dump($x);
}

Otherwise, PHP throws an exception when the script terminates, but that is outside of your try/catch block

EDIT

The exception thrown on script termination if your object hasn't been manually destroyed can't be caught because you can't wrap try/catch around the PHP's internal termination handling that destroys the object; and this is what results in a fatal error

Fatal Error: Uncaught Exception

So this is what the documentation is warning you about

Upvotes: 6

Related Questions