为什么尝试抓不工作?我究竟做错了什么? (PHP)

时间:2016-11-25 19:41:43

标签: php

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

如果php文件不存在,我想要它显示error。 但它不起作用......

我做错了什么?

或者这只是不能用于php中的try catch吗?

2 个答案:

答案 0 :(得分:1)

如果您要返回'错误'并希望相反看到实际的异常消息,这一行应该替换你的 $ content ='错误';

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

然后你的函数将返回$ content,包括消息错误字符串。

答案 1 :(得分:1)

它没有工作,因为失败的include不会抛出异常,它会发出警告。因此,永远不会执行string type,name; bool isChocolate; double weight, price; string line = "Candy Red Riding Hood,0.17,2.21,true"; if (line.ToLower().Contains("candy")) { type = "candy"; line = line.ToLower().Replace("candy", " ").Trim(); if (line.ToLower().Contains("true")) { isChocolate = true; line = line.ToLower().Replace("true", " ").Trim(); } else if(line.ToLower().Contains("false")) { line = line.ToLower().Replace("false", " ").Trim(); } } 块,因为只有在有异常的情况下才会输入它。您可以检查文件是否存在,如果没有,则抛出异常。

catch

如果目标文件不存在,则会输出

  

错误:文件不存在:[path-to-file]

您的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(); } 变量中的

参考