There are no easy portable ways to do this in C++
that I am aware of. There are some reasonably complicated ways to get full stack trace using Operating System specific calls.
The simplest way I use to get the source of the exception is using MACROS.
Macros are not recommended where they can be avoided but this is one of the few places they prove useful.
I tend to uses something slightly more complicated than this but this is the basics of it:
#ifndef NDBUG
#define throw_runtime_error(msg) \
throw std::runtime_error(std::string(msg) \
+ " line: " + std::to_string(__LINE__) \
+ " file: " + std::string(__FILE__))
#else
#define throw_runtime_error(msg) throw std::runtime_error(msg)
#endif
void doSomething2(){
throw_runtime_error("My runtime error.");
}
void doSomething1(){
doSomething2();
}
int main()
{
try
{
doSomething1();
}
catch(std::exception const& e)
{
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
You don't get a full trace but you do get to see where the exception was thrown. The MACRO only includes the debugging information when NDBUG
is not set because release builds should set that macro to disable debugging information.