It's possible to design your exceptions to include source file names & line numbers. In order to do so, you need to create a class derived from std::exception
to contain the information. In the example below, I have a library of exceptions for my application including my_exception
. I also have a traced_error
which is a template exception class derived from my application-level exceptions. The traced_error
exception holds information about the filename & line number, and calls the application-level exception class' what()
method to get detailed error information.
#include <cstdlib>
#include <string>
#include <stdexcept>
#include <iostream>
using namespace std;
template<class EX>
class traced_error : virtual public std::exception, virtual public EX
{
public:
traced_error(const std::string& file, int line, const EX& ex)
: EX(ex),
line_(line),
file_(file)
{
}
const char* what() const
{
std::stringstream ss;
static std::string msg;
ss << "File: " << file_ << " Line: " << line_ << " Error: " << EX::what();
msg = ss.str().c_str();
return msg.c_str();
}
int line_;
std::string file_;
};
template<class EX> traced_error<EX> make_traced_error(const std::string& file, int line, const EX& ex)
{
return traced_error<EX>(file, line, ex);
}
class my_exception : virtual public std::exception
{
public:
my_exception() {};
const char* what() const
{
return "my_exception's what";
}
};
#define throwx(EX) (throw make_traced_error(__FILE__,__LINE__,EX))
int main()
{
try
{
throwx(my_exception());
}
catch( const std::exception& ex )
{
cout << ex.what();
}
return 0;
}
The output of this program is:
File: .\main.cpp Line: 57 Error:
my_exception's what
You could also redesign this so that the application-level exceptions derive from traced_error
instead of the other way round, in case you would rather catch specific application-level exceptions. In your catch
, you can log the error to a log file & create a dump file using MiniDumpWriteDump().