出现错误时在if/else块之间切换

switch between if/else blocks on error

本文关键字:else 之间 if 错误      更新时间:2023-10-16

我正在寻找一种在发生错误时在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
}

我玩过尝试/投掷/接球,但似乎接球必须遵循尝试语句。任何想法/建议都将不胜感激!

当我遇到这种情况时,我用else块中需要的代码创建了一个单独的函数。然后,只要需要(如果发生错误,并且在else块中),我就会调用函数。

看起来你不可能有一个"else":

int error = 0;
if( choice==1 ) {
    // Something happens
    error = 1;
}
if( error == 1 || choice == 2 ) {
    // Do things
}

您确实希望将其拆分为两个不同的条件块。毕竟,你并不是说"其他"。

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