“Fatal error: Exception thrown without a stack frame in Unknown on line 0″ explained

Several errors in PHP can throw you off if you are not familiar with them. One is of course the cryptic “Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM” which happens when the PHP compiler encounters an unexpected double colon (“::”) somewhere in your code. (Actually, “paamayim nekudotayim” is Hebrew for “double colon”). You probably made a typo somewhere. Fortunately, this one comes with a filename and a line number so debugging and fixing this error is easy.

An error which is extremely hard to debug is “Fatal error: Exception thrown without a stack frame in Unknown on line 0“. As you can see, the error does not include a filename or line number so if you o not know what can cause this error you can be left completely clueless.

For the error to appear, four conditions have to be met:

  1. You need to have set a custom error handler using set_error_handler().
  2. Your error handler should throw an Exception if an error is triggered.
  3. You need to have set a custom exception handler using set_exception_handler().
  4. An error occuring when handling the exception.

The first three conditions are pretty common. Since PHP can have both errors and exceptions, you need a common way to deal with both of them. An easy solution is converting errors into exceptions using a custom error handler and the ErrorException. Nearly all PHP functions can trigger errors so you cannot really do without error handling.

The following code example will trigger the dreaded Fatal error: Exception thrown without a stack frame in Unknown on line 0 error:

<?php

set_error_handler('myerrorhandler');
set_exception_handler('myexceptionhandler');

function myerrorhandler($errno , $errstr, $errfile, $errline, $errcontext) {
	throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

function myexceptionhandler($exception) {
	$oops = 1/0; // Division by zero is a fatal error
}

echo $undefined_variable;

The example also demonstrates converting errors to ErrorExceptions. In this example a division by zero error is triggered in the exception handler. This is then converted to an ErrorException. When the ErrorException triggers another error in the exception handler, PHP gives up and throws the “Exception thrown without a stack frame in Unknown on line 0″-error.

One way to solve this is wrapping everything in the exception handler in a try catch statement and then discarding the ErrorException after catching it.

Knowing what causes the error hopefully makes it a lot easier to debug the problem. If you have any questions after reading this post, feel free to post them in the comments below.


About this entry