5

私のプログラムは次のとおりです:(Linux上)

// Ex. 2 of Exception Handling
// Here divn() raises the exception but main() will be the exception handler

#include<iostream>
using namespace std;

int divn(int n, int d)
{
    if(d == 0)
        throw "Division by ZERO not possible ";

    return n/d;
}

main()
{
    int numer, denom;
    cout << "Enter the numerator and denominator : ";
    cin >> numer >> denom;
    try
    {
        cout << numer << " / " << denom << " = " << divn(numer,denom) << endl;
    }
    catch(char *msg)
    {
        cout << msg;
    }
    cout << "\nEnd of main() \n ";
}

/* 分母を 0 にすると、例外がスローされ、指定されたエラー メッセージが表示されます。denom に 0 を入力すると得られる出力は次のとおりです。

administrator@ubuntu:~/FYMCA/CPP_class$ g++ prog110.cpp administrator@ubuntu:~/FYMCA/CPP_class$ ./a.out 分子と分母を入力してください: 12 0 'char const*' のインスタンスをスローした後に呼び出されて終了します 中止されました(コアダンプ)

問題を解決するにはどうすればよいですか?

4

4 に答える 4

-1

簡単な修正は、次のようにステートメントを先頭に追加することです。

char * err = "Division by ZERO not possible";

次に、に変更throwしますthrow err;

これは、コンパイラが文字列リテラルにストレージを割り当てる方法に関係しています。

于 2013-04-03T17:59:35.800 に答える