3

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

这是这种情况的“最佳实践”吗?还是有更标准的方法来做到这一点?

<?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
  }
?> 
4

1 回答 1

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
         }

因为这InvalidArgumentException也是Exception代码重复的典型案例,并且本身可以简化为:

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

现在,您询问这是否是好的做法的那条线已经消失了。所以我想即使使用这种纯粹系统的方法来删除重复代码,也可以回答这个问题:不,这不是一个好习惯。那是代码重复。

旁边——正如已经评论过的——重新抛出异常没有任何价值。所以代码甚至可以简化为:

         $this->x = $this->functionThatMightThrowException($filename);
         $this->y = $this->doSomethingElseThatMightThrow();

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

于 2013-08-20T20:27:48.447 回答