PHP从构造函数重新抛出异常

Nei*_*man 3 php oop exception-handling

只是想知道这是否是一种常见做法.基本上构造函数正在调用一些失败的初始化函数.我的想法是,将异常重新抛回到创建对象的位置是有意义的,因为这是发送实际输出的地方.

对于这种情况,这是"最佳做法"吗?或者有更标准的方法来做到这一点?

<?php
  class a {   
        private $x;
        private $y;
        function __construct($filename) {
             try {
                 $this->x = $this->functionThatMightThrowException($filename);
                 $this->y = $this->doSomethingElseThatMightThrow();
             }
             catch(InvalidArgumentException $e) {
                  throw $e;    //is this a good practice or not???
             }
             catch(Exception $e) {
                  throw $e;    //again
             }
         }

         //rest of class definition
    }

  // then somewhere else where the object is created and output is being sent
  $fn = "blah.txt";
  try {
    $a = new a($fn);
  }
  catch (InvalidArgumentException $e) {
     //actually handle here -- send error message back etc
  } 
  catch (Exception $e) {
     //etc
  }
?> 
Run Code Online (Sandbox Code Playgroud)

hak*_*kre 5

我们只看到这部分代码:

         try {
             $this->x = $this->functionThatMightThrowException($filename);
             $this->y = $this->doSomethingElseThatMightThrow();
         }
         catch(InvalidArgumentException $e) {
              throw $e;    //is this a good practice or not???
         }
         catch(Exception $e) {
              throw $e;    //again
         }
Run Code Online (Sandbox Code Playgroud)

因为InvalidArgumentException是还有一个Exception,这是可以被减少到的代码复制和每知的典型病例:

         try {
             $this->x = $this->functionThatMightThrowException($filename);
             $this->y = $this->doSomethingElseThatMightThrow();
         }
         catch(Exception $e) {
              throw $e;    //again
         }
Run Code Online (Sandbox Code Playgroud)

现在,您询问这是否良好实践的路线已经消失.所以我想即使采用这种纯系统的方法来删除重复的代码,问题也可以回答:不,这不是好的做法.这就是代码重复.

接下来 - 已经评论过 - 重新抛出异常没有任何价值.所以代码甚至可以减少到:

         $this->x = $this->functionThatMightThrowException($filename);
         $this->y = $this->doSomethingElseThatMightThrow();
Run Code Online (Sandbox Code Playgroud)

所以我希望这会有所帮助.代码与以前完全相同,没有区别,只需要更少的代码,这总是受欢迎的.