I wrote a few custom exceptions for my software package, all of which extend std::exception
. However, when I catch thrown exceptions in my driver file, nothing is printed by e.what()
. I am catching by constant reference as well. What am I missing here?
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;
}
}
OUTPUT
Program exited with errors
There is no mention of the exception's error message. How come?