tags:

views:

139

answers:

4

hello.

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

Thanks

+3  A: 

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 << e.what() << endl;
   }
}
anon
I put clarifications about my requirements
aaa
@aaa If your code is intended to be used from non-C++ code, it should be given C linkage and should never allow exceptions to escape into the calling code.
anon
what is a good way to communicate terminal problems into main program?I need some facility to print error string, without relying on fortran output
aaa
anon
okay, I will do something along those lines.Thanks
aaa
Return error codes via your C Linkage interface, and provide your library users a method to convert those error codes into strings.
Mark B
@Mark one potential problem I could have would be due to multithreading in C++ code. I will have to think of something.
aaa
+3  A: 

You could write in main:

try{

}catch(const std::exception &e){
   std::cerr << e.what() << std::endl;
   throw;
}
EFraim
I put some clarifications.In principle I can go with something like this if there is no way around it
aaa
And note that this has the downside of blowing away your callstack which g++ would normally preserve in the core file for uncaught exceptions.
Mark B
+2  A: 

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.

Kirill V. Lyadvinsky
okay, I think I will put try catch with message print in fortran/c wrappers and throw from there. then I will let C++ interface handle exceptions on its own
aaa
+1  A: 

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.

frankc