1

私は例外を使い始めており、いくつかのイベントやエラーをより正確に処理するために、から派生した独自のタイプの例外を作成しましたstd::exception。これまでのところすべてうまくいきましたが、メソッドwhat()が何も出力しない場合があることに気付きました。例外は適切にスローされてキャッチされますが、メソッドによって正常に出力される説明メッセージがwhat()常に画面に表示されるわけではありません。メッセージの出力を終了した前の実行と同じパラメーターで発生する可能性があり、完全にランダムに見えます。

ここに私の例外があります:

class MyException : public std::exception
{
    public:
        MyException() throw() {}
        ~MyException() throw() {}
        virtual const char *what() const throw()
        {
            return "general exception\n";
        }
};

class FileError : public MyException
{
    public:
        FileError(std::string nFileName) : MyException(), fileName(nFileName) { }
        ~FileError() throw (){ }
        virtual const char *what()
        {
            std::ostringstream oss;
            oss << "Error with file : \"" << fileName << "\"." << std::endl;
            return (oss.str()).c_str();
        }
    protected:
        std::string fileName; 
};

そして私に問題を引き起こすコンテキスト:

try
{
    QFile sourceFile(sourceFileName);
    if(!sourceFile.open(QIODevice::ReadOnly))
        throw FileError(sourceFileName.toStdString());
    sourceFile.close();
}
catch(FileError &e)
{
    std::cout << "error file catch " << std::endl;
    std::cout << e.what();
    terminate();
}

「エラーファイルキャッチ」は常に出力されますが、「ファイルでエラーが発生しました...」と表示されることがあります。私が間違っていることは何ですか?ありがとう

4

2 に答える 2

4

一時的な std::string の内容へのポインターを返しています。

于 2012-09-24T18:44:14.260 に答える
2

You aren't flushing std::cout prior to calling terminate (assuming that is std::terminate). I would recommend using std::endl (which is a newline and a flush) at the point where it's output, and not inside FileError::what()

catch(FileError &e)
{
    std::cout << "error file catch " << std::endl;
    std::cout << e.what() << std::endl;
    terminate();
}

Also, as pointed out by @Yuri Kilocheck, you're returning a pointer to a temporary string, invoking UB. The usual solution is to have a string member that is built when what() is executed (if there is a failure building the string, return some pre-defined version).

于 2012-09-24T18:40:58.577 に答える