Reputation: 2611
I have some custom exception like below
class myexception: public exception
{
virtual const char* what() const throw()
{
return "My exception happened";
}
} myex;
void testException(){
throw myex;
}
void doSomething2(){
testException();
}
void doSomething1(){
doSomething2();
}
int main () {
try
{
doSomething1();
}
catch (exception& e)
{
cout << e.what() << '\n';
}
return 0;
}
so in the main function I can not know the caller of a throw(which function has thrown exception), how to get that details ?
Upvotes: 3
Views: 1702
Reputation: 1701
this should be helpful:
How to automatically generate a stacktrace when my gcc C++ program crashes
you can find out way to print call stack and print that in exception handler.
Upvotes: 1
Reputation: 48615
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.
Upvotes: 1