异常扩展了std :: exception但错误消息不会打印

时间:2017-03-01 12:55:15

标签: c++ exception exception-handling

我为我的软件包写了一些自定义异常,所有异常都延伸std::exception。但是,当我在驱动程序文件中捕获抛出异常时,e.what()不会打印任何内容。我也在不断引用。我在这里缺少什么?

exceptions.h

#include <sstream>

struct FileNotFoundException : public std::exception
{
    const char * _func;
    const char * _file;
    int _line;
    FileNotFoundException(const char * func, const char * file, int line) : _func(func), _file(file), _line(line) {}

    const char * what() const throw()
    {
        std::stringstream stream;
        stream << "FileNotFoundException: Could not find file" << std::endl << "  In function " <<
            _func << "(" << _file << ":" << _line << ")";
        return stream.str().c_str();
    }
};

io.cpp

#include "exceptions.h"

void loadFile(const std::string &path_to_file)
{
    std::ifstream file(path_to_file.c_str());
    if (!file.is_open())
    {
        throw FileNotFoundException(__func__, __FILE__, __LINE__);
    }
    // ...
}

runner.cpp

#include "exceptions.h"
#include "io.h"

#include <iostream>


int main(int argc, char ** argv)
{
    try
    {
        loadFile("test.txt");
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << "Program exited with errors" << std::endl;
    }
}

输出

  

程序退出并显示错误

没有提及异常的错误消息。怎么样?

0 个答案:

没有答案