2013-08-20 98 views
3

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

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

<?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 
    } 
?> 
+0

如果你只是要重新抛出它,你为什么首先要抓住它? – PeeHaa

+0

我会说这是多余的。别担心。让他们通过未被捕获的流行,不需要重新抛出它们。 – hakre

+2

如果您没有捕捉到特定的异常,它将简单地执行备份执行链。捕捉并重新抛出相同的异常通常是毫无意义的。通常你只能抓到你实际想要处理的东西,然后让其他人上楼去处理。这就像自助餐:如果你不想吃东西,那么不要把它放在你的盘子上。 –

回答

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

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

+0

所以你说的“$ A = new a($ fn);”的try/catch块足以发现异常?无需额外的尝试块在构造函数中,因为异常会找到它的方式吗? –

+0

好吧,定义*足够*,但阅读如何异常通常在PHP中工作http://php.net/language.exceptions基本上导致这样的结论,是的。 – hakre

+0

我应该提到有多个catch块,因为函数为特定情况抛出InvalidArgumentException,并且需要以不同于其他一些随机可能性的方式进行处理。 –