简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM