我正在寻找一种在发生错误时在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语句。任何想法/建议将不胜感激!
答案 0 :(得分:2)
当我遇到这种情况时,我使用else
块中想要的代码创建了一个单独的函数。然后我在需要时调用函数(如果发生错误,并在else
块中)。
答案 1 :(得分:1)
看起来你可能没有“其他”:
int error = 0;
if( choice==1 ) {
// Something happens
error = 1;
}
if( error == 1 || choice == 2 ) {
// Do things
}
答案 2 :(得分:1)
你真的想把它分成两个不同的条件块。毕竟,你并不是指“其他”。
if(choice==1)
{
//if error occurs....
}
if(choice==2 || error)
{
//switch to this block
}