Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ runtime, display exception message

Tags:

c++

exception

People also ask

What is a runtime exception C?

These errors indicate either a bug in your app's code, or a condition that the runtime library can't handle, such as low memory. End users of your app may see these errors unless your write your app to prevent them, or to capture the errors and present a friendly error message to your users instead.

How do you display an exception message in C++?

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.

How do I show exception messages in .NET core?

To handle exceptions and display user friendly messages, we need to install Microsoft. AspNetCore. Diagnostics NuGet package and add middleware in the Configure() method. If you are using Visual Studio templates to create ASP.NET Core application then this package might be already installed.


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;
   }
}

You could write in main:

try{

}catch(const std::exception &e){
   std::cerr << e.what() << std::endl;
   throw;
}

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.


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.


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