2016-01-21 36 views
-1

我試圖捕獲異常,但不可能,只是正在錯誤消息PHP異常不要再追

try{ 
    echo 'test'; 
    require_once "jj.php"; 
    return true; 
} catch (Exception $ex) { 
    throw new Exception("error occured"); 
} 



Warning: require_once(jj.php): failed to open stream: No such file or directory in C:\xampp\htdocs\corporate-wellness\module\Survey\src\Survey\Repository\QuestionRepository.php on line 
+0

退房['file_exists'(HTTP:// PHP .net/manual/en/function.file-exists.php)並觸發/拋出你自己的錯誤/異常。 – Script47

+3

[this]的副本(http://stackoverflow.com/questions/5369488/try-catch-cannot-work-with-require-once-in-php) – DevDonkey

回答

5

這不是一個例外(但警告),所以你不能簡單地抓住它。

您可以抑制警告,而不是(在這種情況下不推薦)或使用的東西,以驗證是否file exists

所以,像

try { 
    if(!file_exists("jj.php")) { 
     throw new Exception("File doesn't exists"); 
    } 
    require_once "jj.php"; 
    return true; 
} catch (Exception $ex) { 
    // if you would you can handle exception here or you can simply 
    // throw exception without try - catch block 
} 
+0

如果你已經打算扔一個錯誤? – Script47

+0

@ Script47:你是對的,你不需要它,除非你想以不同的方式處理異常,而不是直接進入if語句 – DonCallisto