【问题标题】:switch between if/else blocks on error错误时在 if/else 块之间切换
【发布时间】:2012-03-26 10:56:04
【问题描述】:

我正在寻找一种在发生错误时在 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 语句。任何想法/建议将不胜感激!

【问题讨论】:

  • 您可以将else if 部分的主体放在一个函数中,然后从两个地方调用它

标签: c++ exception-handling error-handling try-catch


【解决方案1】:

你真的想把它分成两个不同的条件块。毕竟,你的意思不是“其他”。

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

【讨论】:

    【解决方案2】:

    看起来你不能有一个“else”:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-02-24
        • 1970-01-01
        • 2021-06-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多