2013-08-12 44 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