1
function TriggerContent($c, $db){
    try {
        include 'pages/' . $c . '.php';
        $content= getContent();
    } catch (Exception $e){
        $content = 'Error';
    }
    return $content;
}

What I want it do is display the error if the php file doesn't exists. But it doesn't work...

What am I doing wrong?

Or will this just not work with try catch in php?

Pankaj Makwana
  • 3,030
  • 6
  • 31
  • 47
H Skee
  • 49
  • 2
  • 10

2 Answers2

1

If you are returning 'Error' and hoping instead to see the actual Exception message this line should replace your $content = 'Error';

$content = 'Caught exception: '.$e->getMessage();

Then your function will return $content including the message error string.

WEBjuju
  • 5,797
  • 4
  • 27
  • 36
1

It's not working because a failed include doesn't throw an exception, it throws a warning. Therefor the catch block will never be executed, as you'll only enter it if there is an exception. You can just check if the file exists, and if it doesn't, throw an exception.

try {
    $page = 'pages/' . $c . '.php';

    if (!file_exists($page))
        throw new Exception('File does not exist: ['.$page.']');

    include $page;
    $content = getContent();

} catch (Exception $e){
    $content = 'Error: '.$e->getMessage();
}

If the targeted file doesn't exist, it will output

Error: File does not exist: [path-to-file]

in your $content variable.

Reference

Qirel
  • 25,449
  • 7
  • 45
  • 62
  • I will accept this as the answer, but I actually thought try catch would work the same as in a language like C# where it always throw's an exception if something doesn't work... – H Skee Nov 25 '16 at 20:05
  • PHP has multiple types of errors, not everything is an exception. You've got notices, warnings (these two *"can"* be ignored), exceptions (can be catched), and fatal errors (stops the execution). So if you want to handle something as an exception (in a try/catch) you'll have to specifically throw an exception. You also have `require` as opposed to `include`, but that throws a "fatal error", which isn't catchable (I might be wrong about that, but not by default anyway). – Qirel Nov 25 '16 at 20:09