Throw runtime warnings in C++

danijar picture danijar · Mar 16, 2013 · Viewed 9.2k times · Source

I started using exceptions some weeks ago and now I wonder if there is a way to just throw a warning. This warning shouldn't force the application to exit if it isn't caught. I will give you an example in what situation I would like to use that.

There is a system that appends properties to unique ids. When I somehow try to add a property to a not yet existing id, the system should create that id internally for me, add the property to it afterwards and return the result. Of course this can't be done quietly. But since the application could stay running, I do not want to throw an exception.

How can I notify that something wasn't quite correct, but the system runs on?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Mar 16, 2013

Who do you want to notify? The end-user? In which case, just write a suitable message to cerr. Or better, write a wrapper function (e.g. LOG_WARNING()) to do it in a controlled manner. Or better still, use a logging framework.


But since the application could stay running, I do not want to throw an exception.

Note that an exception doesn't have to result in the application terminating. You can catch an exception higher up the stack, and handle the situation appropriately.