2013-03-13 123 views
0

有可能告訴我們是否在外部try..catch塊內?PHP:檢測我們是否在外部try..catch塊內

實施例的代碼(請取爲只是作爲例子):

<?php 
class Foo{ 
    public function load($id) 
    { 
     try{ 
      // Model throw NodeNotFoundException only in rare cases 
      $node = $this->getModel()->loadById($id); 
     } 
     catch(NodeNotFoundException $nle) 
     { 
      // @here I need to tell if im in the First case or in the Second one, 
      // detecting the external try..catch block 
      if(externalTryCatchBlock() === true) 
      { 
       throw $nle; 
      } 
      else 
      { 
       watchdog('Unable to find node', $nle->details); 
      } 
      return false; 
     } 
     catch(Exception $e) 
     { 
      watchdog('Something gone wrong.'); 
      return null; 
     } 
     return $node; 
    } 
} 

$foo = new Foo(); 

// First case, no external try..catch 
$node = $foo->load(2); 

// Second case: we need to do here something different if the node load 
// throw an exception 
try{ 
    $another_node = $foo->load(3); 
} 
catch(NodeNotFoundException $nle) 
{ 
    watchdog('Unable to find node, using default.'); 
    $another_node = Bar::defaultNode(); // This is JUST for example 
} 

// Do something with $another_node 
?> 

基本上,我需要重新拋出的異常(NodeNotFoundException)僅當有另一個catch塊等待它,以避免Fatal error: Uncaught exception

當然,我可以,爲上面的考試,使用2加載方法(一個與另一個w/o try..catch),但我想避免這一點..我很想知道是否有可能檢測try..catch塊在PHP中

回答

0

這不是一段代碼的工作,擔心它是如何調用的。代碼總是拋出一個異常,故事結束。因此該代碼具有「屬性」 可能會拋出異常X

/** 
* Does something. 
* 
* @return mixed Some value. 
* @throws SomeException if something went wrong. 
*/ 
function foo() { 
    ... 
} 

現在,無論是誰調用此代碼需要準備爲它在任何時候拋出異常。代碼無法擔心是否有人能夠發現異常。如果出現異常情況,它會拋出異常,因爲它無法繼續執行其工作。需要爲此準備調用者,而不是其他方式。

+0

正如我之前所說,這僅僅是一個例子,以及一種想到的好奇心。順便說一下,我們可以有不同種類的特殊情況 - 對於上面的例子,如果沒有找到節點是一個錯誤,但是如果節點是另一個實體假裝該節點存在的字段,我們必須做其他事情。 – Strae 2013-03-13 14:12:32

+0

說了這些,我不知道*是否有一個合理的編程方式來確定你是否在'try..catch'塊中,但我不認爲它存在。由於上面提到的原因,聽起來像是一個壞主意,有這樣的事情,我從來沒有聽說過。 – deceze 2013-03-13 14:13:20