2011-11-10 10 views
0

試してもキャッチが正しく動作しないようです。 try/catchを実装するときは、あなたが言った文字列を「投げる」と思われます。そして、あなたが望むなら、プログラムを続けましょう。まあ、私の言うことを言っているとは言いませんし、それを続けるのではなく、代わりにこれが中止されてしまいます。試してみる/キャッチ&スローが正常に動作しない

デバッグエラー! Blah blah blah.exe R6010 -abort()が呼び出されました(アプリケーションをデバッグするために再試行を押してください)

「私はそれ以上の項目を追加しようとしています。その後、プログラムを続行します。 LinkedListですが、30以上のノードを持つことはできません。それは私がそれを望む方法ではなく、30以上を追加しようとすると停止します。私は間違って何をしているのかよく分かりません。

Main: 
    Collection<int> list; 

    for(int count=0; count < 31; count++) 
    {  
     try 
     { 
      list.addItem(count); 
      cout << count << endl; 
     } 
     catch(string *exceptionString) 
     { 
      cout << exceptionString; 
      cout << "Error"; 
     } 
    } 
    cout << "End of Program.\n"; 

Collection.h: 
template<class T> 
void Collection<T>::addItem(T num) 
{ 
    ListNode<T> *newNode; 
    ListNode<T> *nodePtr; 
    ListNode<T> *previousNode = NULL; 

    const std::string throwStr = "You are trying to add more Items than are allowed. Don't. "; 

    // If Collection has 30 Items, add no more. 
    if(size == 30) 
    { 
     throw(throwStr); 
    } 
    else 
    {}// Do nothing.    

    // Allocate a new node and store num there. 
    newNode = new ListNode<T>; 
    newNode->item = num; 
    ++size; 

    // Rest of code for making new nodes/inserting in proper order 
    // Placing position, etc etc. 
} 

答えて

4

文字列をスローしていますが、文字列へのポインタをキャッチしようとしています。これに

変更あなたのtry/catchブロック:

try 
{ 
... 
} 
catch(const string& exceptionString) 
{ 
    cout << exceptionString; 
} 
あなたが投げているものと互換性のあるタイプを「キャッチ」していないので、あなたがそのアボートメッセージを取得している理由は

、例外はキャッチをバイパスするだけなので、キャッチされていないデフォルトの例外ハンドラの影響を受けて、 "キャッチされない例外"になります。

FYIより標準的な方法は、std :: exceptionオブジェクトをスロー/キャッチすることです。すなわち

try 
{ 
... 
} 
catch(std::exception& e) 
{ 
    std::cout << e.what(); 
} 


... 

throw(std::logic_error("You are trying to add more Items than are allowed. Don't.")); 
+0

これはトリックでした!どうもありがとうございました! :) – Riotson

関連する問題