0

次のコードがあります。

#include "math.h" // for sqrt() function
#include <iostream>
using namespace std;

int main()
{
    cout << "Enter a number: ";
    double dX;
    cin >> dX;

    try // Look for exceptions that occur within try block and route to attached catch block(s)
    {
        // If the user entered a negative number, this is an error condition
        if (dX < 0.0)
            throw "Can not take sqrt of negative number"; // throw exception of type char*

        // Otherwise, print the answer
        cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
    }
    catch (char* strException) // catch exceptions of type char*
    {
        cerr << "Error: " << strException << endl;
    }
}

プログラムを実行した後、負の数を入力し、catch ハンドラーが実行されて出力されることを期待していましたError: Can not take sqrt of negative number。代わりに、プログラムは次のメッセージで終了しました

Enter a number : -9
terminate called after throwing an instance of 'char const*'
Aborted

私の例外が catch ハンドラーでキャッチされなかったのはなぜですか?

4

2 に答える 2

2

const を追加する必要があります。

catch (char const * strException) // catch exceptions of type char*

実際、あなたは を投げていますが、このように一致しないchar const *mutable を期待しています (反対のことをします)。char *

于 2012-06-17T06:54:26.123 に答える
1

そもそも、なぜ糸を投げたりキャッチしたりしているのですか?

例外をスローしてキャッチする必要があります。

次の経験則を常に覚えておいてください

コードに引用符で囲まれた文字列を挿入すると、null で終了する const char が返されます。

于 2012-06-17T07:04:51.097 に答える