2012-03-13 41 views
2

script_a.php處理異常,只有執行的代碼,如果一個異常被拋出不

try { 
    Class1::tryThis(); 
} 
catch (Exception $e) { 
    // Do stuff here to show the user an error occurred 
} 

Class1::tryThis()具有類似:

public function tryThis() { 
    Class2::tryThat(); 
    self::logSuccessfulEvent(); 
} 

的問題是,Class2::tryThat()可以拋出異常。

如果確實會拋出異常,看起來行self::logSuccessfulEvent();仍然被執行。

我如何重構這段代碼,以便self::logSuccessfulEvent()只有當一個異常沒有拋出,但在同一時間讓script_a.php知道什麼時候異常被扔發生?

+0

問題在別的地方 – miki 2012-03-13 16:33:51

+0

「好像是」?如果'tryThat'拋出一個未處理的異常,'tryThis'('self :: logSuccessfulEvent()')**中的下一行將不會運行。** – webbiedave 2012-03-13 16:36:50

+0

@webbiedave和OP:你絕對正確。下一行無法運行,並且它在我沒有意識到的情況下被事先執行。因此,PHP異常按我的預期工作:在當前代碼塊中拋出異常的語句之後沒有執行代碼。 – eoinoc 2012-03-20 11:23:24

回答

5

該函數將返回操作是否成功(TRUE =成功,FALSE =失敗)

public function tryThis() { 
    $success = true; 

    try { 
     Class2::tryThat(); 
     self::logSuccessfulEvent(); 
    } catch(Exception $e) { 
     $success = false; 
    } 

    return $success; 
} 
2

什麼你所描述的似乎並不如此。

代碼:

<?php 
class Class1 { 
    public function tryThis() { 
     echo "Class1::tryThis() was called.\n"; 
     Class2::tryThat(); 
     self::logSuccessfulEvent(); 
    } 

    public function logSuccessfulEvent() { 
     echo "Class1::logSuccessfulEvent() was called.\n"; 
    } 
} 

class Class2 { 
    public function tryThat() { 
     echo "Class2::tryThat() was called.\n"; 
     throw new Exception('Exception generated in Class2::tryThat()'); 
    } 
} 

try { 
    Class1::tryThis(); 
} catch (Exception $e) { 
    echo $e->getMessage(), "\n"; 
} 

輸出:

Class1::tryThis() was called. 
Class2::tryThat() was called. 
Exception generated in Class2::tryThat() 

正如你可以看到,當Class2::tryThat()生成異常永遠不會執行的Class1::logSuccessfulEvent()方法,它不應該(不會)要麼。異常會一直冒泡直到它們被捕獲或產生致命錯誤。一旦發現異常,程序的控制權返回到catch塊之後的代碼。在這種特殊情況下,這意味着程序的控制永遠不會達到日誌記錄方法。

+0

這就是我假定異常會起作用的方式。也許這是一個跡象表明我的代碼在引發異常之前調用方法。 – eoinoc 2012-03-20 10:48:47

相關問題