2012-07-31 64 views
5

當我使用Try/Catch時,有沒有像If/Else運行代碼的方式,如果沒有檢測到錯誤並且沒有Catch?運行代碼,如果沒有趕上Try/Catch

try 
{ 
    //Code to check 
} 
catch(Exception ex) 
{ 
    //Code here if an error 
} 

//Code that I want to run if it's all OK ?? 

finally 
{ 
    //Code that runs always 
} 
+3

爲什麼不在測試結束時添加代碼? – 2012-07-31 11:00:16

+1

因爲您可能希望其他代碼引發的任何異常被外部異常處理捕獲,而不是此內部try/catch塊。在這種情況下,最好的方式(我知道)是使用布爾。 – John 2014-04-07 19:50:16

回答

18

將代碼添加到try塊的末尾。顯然,你永遠只能到達那裏,如果沒有前一個例外:

try { 
    // code to check 

    // code that you want to run if it's all ok 
} catch { 
    // error 
} finally { 
    // cleanup 
} 

你或許應該改變你抓的方式,你只抓住你期望的異常和不平整出的一切,其中可能包括異常拋出»代碼,你想運行,如果一切正常«。

5

只要將它放在可能拋出異常的代碼之後。

如果拋出異常,它將不會運行,如果沒有拋出異常,它將運行。

try 
{ 
    // Code to check 
    // Code that I want to run if it's all OK ?? <-- here 
} 
catch(Exception ex) 
{ 
    // Code here if an error 
} 
finally 
{ 
    // Code that runs always 
} 
9

如果你需要它,如果你try代碼成功始終執行,把它放在你的try塊的結束。只要try塊中的前一個代碼運行,它將一直運行,沒有出現異常。

try 
{ 
    // normal code 

    // code to run if try stuff succeeds 
} 
catch (...) 
{ 
    // handler code 
} 
finally 
{ 
    // finally code 
} 

如果您需要替代的異常處理你「succeded」的代碼,你可以隨時嵌套的嘗試/捕獲:

try 
{ 
    // normal code 

    try 
    { 
     // code to run if try stuff succeeds 
    } 
    catch (...) 
    { 
     // catch for the "succeded" code. 
    } 
} 
catch (...) 
{ 
    // handler code 
    // exceptions from inner handler don't trigger this 
} 
finally 
{ 
    // finally code 
} 

如果你的「成功」的代碼有你的最後,使用後執行一個變量:

bool caught = false; 
try 
{ 
    // ... 
} 
catch (...) 
{ 
    caught = true; 
} 
finally 
{ 
    // ... 
} 

if(!caught) 
{ 
    // code to run if not caught 
} 
1
try { 
    // Code that might fail 
    // Code that gets execute if nothing failed 
} 
catch { 
    // Code getting execute on failure 
} 
finally { 
    // Always executed 
} 
1

我會寫這樣的:如果調用的方法運行良好,則成功僅僅是try

try 
{ 
    DoSomethingImportant(); 
    Logger.Log("Success happened!"); 
} 
catch (Exception ex) 
{ 
    Logger.LogBadTimes("DoSomethingImportant() failed", ex); 
} 
finally 
{ 
    Logger.Log("this always happens"); 
} 
+1

男人,SO有快速的手指。你們應該到倫敦去競爭 – SpaceBison 2012-07-31 11:03:35

+3

一百萬個鍵盤上有一百萬只猴子,有一百萬個StackOverflow帳戶可能會很快產生正確答案:) – Polynomial 2012-07-31 11:05:41