views:

55

answers:

2

Let's say were using custom extensions of the Exception class to handle custom exceptions, like this for example:

$testObject = new testClass();

and a autoload like this:

function __autoload($class_name) {
    $file = $class_name.'.php';
    if (file_exists($file)) {
        include $file;  
    }else{
        throw new loadException("File $file is missing");
    }
    if(!class_exists($class_name,false)){
        throw new loadException("Class $class_name missing in $file");
    }
    return true;
}

try {
    $testObject = new testClass();
}catch(loadException $e){
    exit('<pre>'.$e.'</pre>');
}

the file testClass.php does not exist, so a loadException is called with the message: File testClass.php is missing. (and all the other details...line number etc)

all was fine, until i decided to hide all the errors and instead display a 404 page (or a 500 page...), so naturally i thought to add a loadErrorPage function.

class loadException {

...

    function loadErrorPage($code){
        $page = new pageClass();
        echo $page->showPage($code);
    }
}

...

try {
    $testObject = new testClass();
}catch(loadException $e){
    $e->loadErrorPage(500);
}

but this has the obvious problem that if the testClass.php AND pageClass.php files are missing, then a fatal error is shown instead of the preferred 404 page.

I'm confused :S How do I elegantly handle this exception within a exception handle?

A: 

Well, you could always just not delete pageClass.php...

I'm assuming that's just one file, shouldn't be too hard to make sure it doesn't disappear, in the same way you're making sure the file which has your __autoload function in it doesn't go anywhere.

Matti Virkkunen
well, that would be the easy way out :), obviously the file is not going anywhere. Unless a strange site owner comes along and deletes this file out of pure boredom!
YuriKolovsky
Trying to cover for each and every ludicrous runtime error will make you a sad coder, you know...
Matti Virkkunen
:(this is actually one of the more common errors
YuriKolovsky
+1  A: 

If class pageClass does not exist and cannot be loaded by your autloader $page = new pageClass(); in your method loadErrorPage() will cause another exception. You'd have to catch this exception and then do something without that class.

function loadErrorPage($code){
  try {
    $page = new pageClass();
    echo $page->showPage($code);
  }
  catch(Exception $e) {
    // header(...500);
    echo 'fatal error: ', $code;
  }
}
VolkerK
does not work for me :S
YuriKolovsky
ok created a specific test case, it does work, i wonder why it does not work in the actual application.
YuriKolovsky