2017-06-05 7 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

はい私は 'キャッチ'をしました、それは動作しますが、私が探しているのは、 'キャッチ 'に到達してもプログを続ける方法です。 – 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のケースではオプションではないかもしれません。たぶん "uplay"コードは第三者のライブラリです。 – Dialecticus

+0

私はそれを避けることができれば十分ですが、私はこの種のパターンを奨励したくありません。一般的に、例外は失敗する可能性がありますが、期待されないものです。この場合、彼らは失敗を予期しているので、代替メカニズムを使用すべきです。 – Mgetz

関連する問題