2017-06-05 21 views
-5

我已經搜索了幾次,但我有點沒有找到我真正想要的東西。即使有異常,也希望程序繼續

我正在與特殊處理(try/catch),我發現這個障礙。如果程序發現異常,則終止。

我試過在catch部分調用函數,但它仍然終止。

void exception_handle() //This is for handling exception if user inputs a char instead of int// 
{ 
user_play uplay; 
try 
{ 
    uplay.usersentry(); 
} 
catch(std::runtime_error& e) 
{ 
    cout<<"Input a string bro, not a character"<<endl; 
    user_input(); 
} 
} 

這裏是類:

class user_play //this class is for letting user play the game by allowing them to enter desired number in the desired empty space// 
{ 
public: 
void usersentry() 
    { 
    int tempdata; 
    retry: 
    cout<<"\n\n Enter the row and coloumn where you want to enter data"<<endl; 
    cin>>i>>j; 
     if (i>=1 && i<=9 && j>=1 && j<=9) 
     { 
      cout<<"\n Enter your desired value to put in that place"<<endl; 
      cin>>tempdata; 
      if(tempdata>=1 && tempdata<=9) 
      { 
       data=tempdata; 
      } 
      else 
      { 
       throw std::runtime_error("Soduku contains numbers from 1 to 9 only.Please try again"); 
       loops++; 
      } 
     } 
     else 
     { 
      throw std::runtime_error("Soduku row exists between 1 and 9 only.Please try again"); 
      loops++;  
     } 
    } 
}; 

下面是函數(這是不完整的,因爲我想debugg)當你看到我打過電話的功能

int user_input() //this one is for taking correct value from user and storing it in its respective place// 
{ 
a=0; 
//Object Declaration// 
rowrules rr; 
columnrules cr; 

//for handling the program exceptions 
exception_handle(); 

//rules for row and column 
//rr.rrules(); 
//cr.crules(); 
//ruleselect(); 
//i--; 
//j--; 
if(a==0) 
{ 
    soduku[i-1][j-1]=data; 
    return soduku[i-1][j-1]; 
} 
else 
{ 
    user_input(); 
} 
} 

這裏catch部分但仍然程序終止。我缺少一些基本的東西?還是有其他解決方案/方法/邏輯? 謝謝!

+4

你有沒有嘗試'catch(...)'?如果您需要幫助瞭解爲什麼它不起作用,您將不得不提供[mcve]。 – NathanOliver

+0

是的,我做了'趕上',它的工作原理,但我期待是一種繼續前進即使達到'catch'的方式。 – LoneRanger17

+3

你應該真的包括那些與你的問題無關的代碼部分。 –

回答

0

不可能從引發C++異常的地方繼續執行。 C++異常不是爲此設計的。但它是可以重複,如果發生異常時你想重複碼:

for (bool success = false; !success;) 
{ 
    try 
    { 
     <some code that should be repeated if exception happens> 

     success = true; 
    } 
    catch (...) 
    { 
    } 
} 

注意,在一般情況下,它是一個糟糕的主意,如果發生異常時做絕對沒有。至少在某些日誌文件中寫下某些東西,如果有的話。

+0

或更好,如果預計失敗,請不要使用異常 – Mgetz

+0

@Mgetz在OP的情況下可能不是一個選項。也許「疊加」代碼是第三方庫。 – Dialecticus

+0

夠公平的,但我不想鼓勵這種模式,如果我們可以避免它。一般而言,異常是針對可能會失敗但不期望的事情。在這種情況下,他們期望失敗,所以他們應該使用替代機制。 – Mgetz

相關問題