![](/img/trans.png)
[英]In PHP, using DomDocument getElementByID not working? What am I doing wrong?
[英]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;
}
我想要做的是顯示error
如果php文件不存在)。 但這行不通...
我究竟做錯了什么?
還是將它與try catch in php不兼容?
如果您返回“錯誤”並希望看到實際的異常消息,則此行應替換您的$ content ='錯誤';
$content = 'Caught exception: '.$e->getMessage();
然后,您的函數將返回$ content,包括消息錯誤字符串。
它不起作用,因為失敗的包含不會引發異常,而是引發警告。 因此catch
塊將永遠不會執行,因為只有在出現異常時才輸入。 您可以只檢查文件是否存在,如果不存在,則引發異常。
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();
}
如果目標文件不存在,將輸出
錯誤:文件不存在:[文件路徑]
在您的$content
變量中。
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.