Is it possible to know if you're already in an exception in PHP?

915

I have some code in a __destruct() method that sometimes throws an exception. The __destruct() method is being called during another exception and I'm seeing a vague error:

PHP Fatal error:  Ignoring exception from exampleClass::__destruct() while an exception is already active

which is hiding the actual exception that's being called. I'd like to do something like:

public function __destruct() 
{
  try
  {
    // do work here
  }
  catch(Exception $e)
  {
    // check if we're already in an exception and log it
    if(already_in_exception())
    {
      error_log($e->getMessage());
    }
    // normal destruct, re-throw
    else
    {
      throw $e;
    }
  } 
}

Bonus points if it's PHP 5.1.6 compatible!

Thank you in advanced!

959

Answer

Solution:

Your problem isn't because you're throwing an exception from within another, it's because you're throwing an exception from a destructor.

From php.net: http://php.net/manual/en/language.oop5.decon.php I quote:

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

Rethink your logic abit and do this prior to deconstruction.

People are also looking for solutions to the problem: javascript - How to pass the value of an option field as well as an input box via post in jquery/PHP?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.