Catching level 1 errors?

Bear with me for a moment:

$a="some non-object, a string for example";
$a->someMethod();// intentional error for the sake of this example!!
echo " am a following line of code";


$a=new MyClass();// MyClass DOES NOT  contain foo(), 
$a->foo();// intentional error for the sake of this example!!
echo " am a following line of code";

The above code will , of course, produce : “Fatal error: Call to a member function someMethod() on a non-object …” and "Fatal error: Call to undefined function foo() " respectively, which I assume are LEVEL 1 errors?

Is there a way to catch these type “fatal errors” as well as KEEP the script from DYING?
(preferably in a general sense, as opposed to having to wrap a “try” around each line like so:

try {$a->someMethod();}// intentional error for the sake of this example!!
catch{ echo: "Hey! You aren't supposed to do this"};


I have been doing this:

error_reporting( E_ALL | E_ERROR );
function ErrHand($err_no, $err_str,$err_file,$err_line)
 echo "Sorry  You  can't do that. <b>$err_str in   $err_file on line $err_line.</b>";
 //die(); // Just here for protocol. I don't actually want the script to die. 

But ErrHand() gets ignored… and changing the constant fed to error_reporting… just gives no output at all!

Most likely, the answer to my question is is “no.” but I thought I would check with the forum experts as all my research seems to be for naught. all advice would be greatly appreciated.


Using the default exception handler like you show stops the need for Try/Catch blocks you can let it bubble up and be caught on the default exception handler that, for example can redirect the user to a page that will not contain error. Output buffer is required though, just in case a fatal error is generated after part of a page has loaded. You just set ob_start(); at the head of every page.

function redirect_on_error($e) { 
  header("Location: ./some_page.php");

ob_start();// ... the rest of your page code goes here? >

There are some PHP fatal errors that are outside the user state. They can not be caught and will trigger an end script. If you have one of these types of errors (sorry I don’t remember which ones they are) then you can’t do it.

Hope this is what you are after.


Fatal errors are not exceptions, however. They will not be caught by a try/catch block or the exception handler.

Please see “set_error_handler” for further information.

Yes, thanks logic_earth… would’ve helped to check this first so indeed all fatal errors are outside of the user state.