2013-06-22 59 views
0

我對整個try catch塊感到困惑。我明白如果拋出一個異常它執行catch塊,但是我有一個關於在try塊內使用return的問題。瞭解try catch塊

try { 

    //other logic is here 

    //this is in laravel and sends the user back and should stop operation 
    if (foo != bar) { 
     return Redirect::back()->with_message('This auction is closed.', 'error'); 
    } 
} catch (Exception $e) { 
    return $e->getMessage(); 
} 

所以我的問題是:是否可以在try塊內結束操作?我會遇到一個錯誤,其中返回被忽略(或者被認爲是一個異常?)並且代碼繼續?再一次,我對此很新。

回答

1

是的,這是編寫該代碼的完美方法。

在您的代碼將繼續控制運行後退出trycatch塊是在PHP 5.5,最終採納了其他語言的finally塊,可用於運行清理代碼後,必須始終執行的一個案例try塊,不管是否拋出異常。

但是你可能沒有使用5.5。

1

是的,沒關係。如果由於任何原因,Redirect :: back或with_message方法引發異常,您將返回錯誤消息