In g++
and clang++
(in Linux at least) the following typical message is shown after an exception is thrown and not catch (uncaught exception):
terminate called after throwing an instance of 'std::runtime_error'
what(): Bye
For example in:
#include<stdexcept>
int main(){
throw std::runtime_error("Bye");
}
How do I customize the error message while still having full access to the thrown exception?
The documentation (http://www.cplusplus.com/reference/exception/set_unexpected/) mentions set_unexpected
(and set_terminate
) but I don't know how the unexpected_handle
has actual access to the exception being thrown, for example to call e.what()
or something else.
Note: The reason behind this is that I want to customize the message for a more complicated exception class hierarchy that has more information than simple what()
, and I want to display it if such type exception is thrown (but if a simple std::exception&
is thrown the default is the same as the typical.
Note2: According to the two suggestions so far, "customize uncaught exceptions by catching the exceptions." Will look like what follows in the code. I was wondering if there is a way to do the same without adding a try-catch
block to all main()
code that I write.
#include<stdexcept>
int main() try{
....
}catch(std::exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< "otherinfo, like current time\n";
}catch(alternative_exception& e){
std::clog << "terminate called after throwing an instance of '" << typeid(e) << "'\n"
<< " what(): " << e.what() << '\n'
<< " where(): " << e.where() << '\n'
<< " how(): " << e.how() << '\n'
<< "othermember(): " << e.othermember() << '\n';
}
Apart from actually catching the exceptions you care about, std::set_terminate()
and std::current_exception()
(C++11) ought to be enough to do something interesting.