3

C++ でリンク リスト ノードを使用してプライオリティ キューの実装を作成しています。

私はこの言語に慣れていないので、空のキューで pop() 関数が呼び出されたときに例外をスローする方法を誰かが理解するのを手伝ってくれれば、本当に感謝しています。

try and catch 例外処理を使用しようとしましたが、コードで「セグメンテーション違反エラー」が発生し続けます

私のプライオリティ キューは正しく実装されています..push()、isEmpty()、size()、clear() は動作します。pop() も機能しますが、ユーザーが不正な呼び出しを行った場合に例外をスローしたいと考えています。

try {
    if(isEmpty()) {
        throw -1;
    }
}
catch(int n) {
    cout << "ERROR" << n << ": LIST IS EMPTY" << endl;
}
4

2 に答える 2

1

Throwing an integer as an exception really isn't the done thing in c++. You really should create either a new exception for the job or pick one of the existing exceptions std library that might fit situation.

http://www.java2s.com/Tutorial/Cpp/0120__Exceptions/Throwyourownexceptionclassbasedonruntimeerror.htm

Yes the domain says java, but it's a c++ tutorial and has an example of how to create a custom exception derived from std::runtime_error.

于 2012-10-07T23:39:31.980 に答える
1

throw ステートメントで例外をスローします。ないtryか、catch関与しています。例外をキャッチするのは呼び出し元の責任です。

if (isEmpty())
    throw -1;
于 2012-10-08T01:52:48.773 に答える