2013-08-20 99 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,並且需要以不同於其他一些隨機可能性的方式進行處理。 –