Have you ever seen the message “PHP Fatal error:  Exception thrown without a stack frame in Unknown on line 0″ and just couldn’t figure out what was causing it?

I’ve seen this message lots of times, but never really tried to find out the cause, instead I always patched the problem somehow without really understanding what this message means. Turns out, the answer is quite understandable :)

While PHP will maintain a stack trace for each exception thrown in “normal” operation mode, there are certain times, when the environment isn’t capable of doing that. Here are two popular examples, which I both ran into a lot without knowing:

  • Throw an exception within a custom exception handler: When you’re using a custom exception handler, make sure that you do NOT throw an exception inside. This does not work, as PHP is not in normal operation mode while processing an exception. As someone pointed out in the comments for setting a customer exception handler, you can place every line of code of your custom exception handler inside a try-catch-block, dump the exception to error_log() and remove the cause for the exception later on.
  • Throw an exception within a constructor or destructor: If you throw an exception in a constructor, the class will not be constructed properly, thus resulting in an invalid state. Likewise, if you do the same in a destructor, the class might have already been partially destructed. The solution I opted for on this issue is the same as above: Place the code of every con-/destructor inside a try-catch-block. If you don’t do this, be sure that no functions you call from con-/destructors will ever throw an exception.
  • Throwing an exception in any autoload function: I’ve had the same behavior when I tried to throw an exception in any function that got registered with spl_autoload_register(), although half of the time it did work.

I’m sure there are a lot of other causes for this error, if I ever see another one, I’ll update this post.