H Skee
H Skee

Reputation: 49

why is try catch not working? What am I doing wrong? (php)

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?

Upvotes: 1

Views: 2881

Answers (2)

Qirel
Qirel

Reputation: 26450

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

Upvotes: 1

WEBjuju
WEBjuju

Reputation: 6581

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.

Upvotes: 1

Related Questions