Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php中的异常处理_Php_Exception Handling_Try Catch - Fatal编程技术网

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);
}