2013-08-12 51 views
2

我在PHP中捕獲異常時遇到問題如何從另一個類方法中捕獲異常PHP

這是我的代碼。

try { 
require $this->get_file_name($action); 
} 

catch (Exception $e) { 
//do something// 
} 

和被稱爲

private function get_file_name($action) { 

    $file = '../private/actions/actions_'.$this->group.'.php'; 

    if (file_exists($file) === false) { 
    throw new Exception('The file for this '.$action.' was not found.'); 
    } 

    else { 
    return $file; 
    } 
} 

的方法,導致:

Fatal error: Uncaught exception 'Exception' with message $action was not found.' 
Exception: The file for this $action was not found. 

但是如果我把一個try-catch塊的函數內並調用該函數,我能夠趕上例外沒有問題。

我在做什麼錯?

+0

把你的try/catch塊中調用代碼 –

+1

http://stackoverflow.com/questions/5369488/try-catch-cannot -with-require-once-in-php –

+1

[Can not Reproduce](http://3v4l.org/afJjt)你確定提供的代碼示例是被調用的嗎? *(可能是子類)*你得到的異常消息似乎與應該拋出的不匹配。 *(未評估的$行動)* – Touki

回答

1

我看不到所有的類體,但是如果你想使用類外的方法,它應該是Public not Private。檢查

0

嘗試,如果文件您想獲得存在:

var_dump($file = '../private/actions/actions_'.$this->group.'.php'); 

IMO有此路徑沒有文件

+0

...嗯,這是多數民衆贊成在爲什麼他試圖趕上例外....((面掌)) – AndrewMcLagan