2012-03-08 41 views
0

我正在尋找一種在出現錯誤時在if和else塊之間切換的方法。例如:在if/else塊之間進行切換錯誤

cout << "Enter 1 or 2 as your choice..."; 
cin >> choice; 

if(choice==1) { 

//do something here 

//if error occurs.... 

} else if(choice==2) { 

//switch to this else block 

} 

我玩過try/throw/catch但看起來catch必須遵循try語句。任何想法/建議,將不勝感激!

+1

您可以將'else if'部分的主體放在一個函數中,然後從兩個地方調用它。 – Praetorian 2012-03-08 23:08:26

回答

1

看起來你可能只是沒有一個「其他」:

int error = 0; 

if(choice==1) { 

    // Something happens 
    error = 1; 

} 
if(error == 1 || choice == 2) { 
    // Do things 
} 
+0

Doh,謝謝! :) – swiss196 2012-03-08 23:25:00

2

當我遇到這種情況時,我使用代碼else中的代碼創建了一個單獨的函數。然後我在需要時調用函數(如果發生錯誤,並且在else塊中)。

1

你真的想在拆分到兩個不同的條件塊。畢竟,你並不是真正的「別的」。

if(choice==1) 
{ 
//if error occurs.... 
} 
if(choice==2 || error) 
{ 
    //switch to this block 
}