Reputation: 51465
I am using gcc on linux to compile C++ code. There are some exceptions which should not be handled and should close program. However, I would like to be able to display exception string:
For example:
throw std::runtime_error(" message");
does not display message, only type of error.
I would like to display messages as well.
Is there way to do it?
it is a library, I really do not want to put catch statements and let library user decide. However, right now library user is fortran, which does not allow to handle exceptions. in principle, I can put handlers in wrapper code, but rather not to if there is a way around
Upvotes: 36
Views: 63522
Reputation: 382622
GCC shows the message at least since 6.2.0
I had tested it on g++ 6.2.0, Ubuntu 16.10, and now again in g++ 9.3.0 Ubuntu 20.04, and both showed the message, not sure when behavior changed:
#include <stdexcept>
void myfunc() {
throw std::runtime_error("my message");
}
int main() {
myfunc();
}
compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
output containing the my message
error message:
terminate called after throwing an instance of 'std::runtime_error'
what(): my message
Upvotes: 3
Reputation:
Standard exceptions have a virtual what()
method that gives you the message associated with the exception:
int main() {
try {
// your stuff
}
catch( const std::exception & ex ) {
cerr << ex.what() << endl;
}
}
Upvotes: 43
Reputation: 11473
I recommend making an adapter for your library for fortran callers. Put your try/catch in the adapter. Essentially your library needs multiple entry points if you want it to be called from fortran (or C) but still allow exceptions to propigate to C++ callers. This way also has the advantage of giving C++ linkage to C++ callers. Only having a fortran interface will limit you substantially in that everything must be passed by reference, you need to account for hidden parameters for char * arguments etc.
Upvotes: 1
Reputation: 99565
You could use try/catch
block and throw;
statement to let library user to handle the exception. throw;
statement passes control to another handler for the same exception.
Upvotes: 3
Reputation: 13028
You could write in main:
try{
}catch(const std::exception &e){
std::cerr << e.what() << std::endl;
throw;
}
Upvotes: 8