user7025447 user7025447 - 1 year ago 69
PHP Question

Why this Exception can not be handled by catch try method

When i initiate a class which does not exist , It throws the error, I Don't want to halted by that error . So i try

method , But it still giving me same error, Can someone explain why this error is not been catched
I tried

try{$obj = new classname();}
catch(Exception $e){ echo 'class does not exist, move on' ;}

Fatal error: Class 'classname' not found in C:\WampDeveloper\Websites\localhost\webroot\index.php on line 4

Can someone explain why this error can not be catched ?

Is their is another way to catch and handle this kind of errors ?


We can catch
fatal errors by try catch method , So don't say fatal errors can not be handeled by try catch method

Answer Source

Two ways to solve this, use a autoloader that runs a custom written function for each object that does not exist so you can try to "include" a file on demand.

function autoload($objname){
  if(is_readable(($f = '/path/to/class/'.$objname.'.php'))){
    include $f;
  } else {
    throw Exception("$f does not exist");


new classname(); // try to load /path/to/class/classname.php

Or you can upgrade to PHP 7 where the error logic has had little overhaul:


  • Throwable
    • Error
      • ArithmeticError
      • DivisionByZeroError
      • AssertionError
      • ParseError
      • TypeError
    • Exception

So a code like this would work:

  $obj = new classname();
} catch(Error $er){
  echo 'class does not exist, move on';
} catch(Exception $ex){
  // code block threw an exception.
} catch(Throwable $t){
  // Obsolete code, as Throwables are either Error or Exception, that were caught above.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download