php中的异常处理
我有这样一个场景:php中的异常处理,php,exception-handling,try-catch,Php,Exception Handling,Try Catch,我有这样一个场景: Interface ClassInterface { public function getContext(); } Class A implements ClassInterface { public function getContext() { return 'CONTEXTA'; } //Called in controller class public function Amethod1() { try {
Interface ClassInterface
{
public function getContext();
}
Class A implements ClassInterface
{
public function getContext()
{
return 'CONTEXTA';
}
//Called in controller class
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class B implements ClassInterface
{
public function getContext()
{
return 'CONTEXTB';
}
//Called in controller class
public function Bmethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
}
Class Helper {
public function helperMethod(ClassInterface $interface)
{
try {
$this->verifyContext($interface->getContext());
//dosomething
} catch(\Exception $ex) {
throw $ex;
}
}
private function verifyContext($context) {
if (condition1) {
throw new \UnexpectedValueException('Invalid context.');
}
return true;
}
}
我希望调用Amethod1和Bmethod1的控制器类知道进程中抛出的异常类型。是否建议像显示异常一样重新显示异常?
你认为在这种情况下,抛接球结构合理吗?是的,完全合理。但是:您的具体示例可以简化为:
public function Amethod1()
{
try {
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
} catch(Exception $ex) {
throw $ex;
}
}
致:
谢谢你的回答,埃弗特。简化的形式使我意识到,我可以直接在我的控制器类中捕获异常,从而省略Amethod1中的try-catch。即使删除了method1中的try-catch,如果它抛出预期的异常,我仍然可以测试它,对吗?
public function Amethod1()
{
//assuming that Helper is a property of this class
$this->helper->helperMethod($this);
}