简体   繁体   English

为什么试鱼不起作用? 我究竟做错了什么? (PHP)

[英]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. 我想要做的是显示error如果php文件不存在)。 But it doesn't work... 但这行不通...

What am I doing wrong? 我究竟做错了什么?

Or will this just not work with try catch in php? 还是将它与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 ='错误';

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

Then your function will return $content including the message error string. 然后,您的函数将返回$ content,包括消息错误字符串。

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. 因此catch块将永远不会执行,因为只有在出现异常时才输入。 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. 在您的$content变量中。

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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