web-dev-qa-db-ja.com

C ++例外-文字列をスローする

コードに小さな問題があります。何らかの理由で、以下のコードで文字列をスローしようとすると、VisualStudioでエラーが発生します。

#include <string>
#include <iostream>
using namespace std;

int main()
{

    char input;

    cout << "\n\nWould you like to input? (y/n): ";
    cin >> input;
    input = tolower(input);

    try
    {
        if (input != 'y')
        {
            throw ("exception ! error");
        }
    }
    catch (string e)
    {
        cout << e << endl;
    }
}

エラー:

error

リンク: http://i.imgur.com/pYAXLuU.png

8
Jimmy

現在、_const char*_ではなく_std::string_をスローしていますが、代わりにstring("error")をスローする必要があります。

編集:エラーはで解決されます

_throw string("exception ! error");
_
12

文字列を投げることは本当に悪い考えです。

自由にカスタム例外クラスを定義し、その中に文字列を埋め込んでください(または、カスタム例外クラスを _std::runtime_error_ から派生させ、コンストラクターにエラーメッセージを渡して、what()メソッドはキャッチサイトでエラー文字列を取得します)が、notは文字列をスローしません!

14
Mr.C64