C++ why don’t we just throw std::error_code’s ?

So little C++ so much good!
So little but so much good!

The context is here. Please read it first. It is 15-sec detour.

The simple question, that hit me the other day, is why don’t we just throw std::error_code or std::error_conditon.

Let me try and calmly observe.

  • Throw/catch only and only if you really have to
  • This concept is not using RTTI.
  • This is not dynamic types catching.
  • This is throw and catch by value.

What are the drawbacks of this for new projects? There must be some, but right now I am having difficulties to find them serious drawbacks.

For throwing this from public API, this renders the API not “exception friendly”. But right now, it seems we have the right not to care. That is the sentiment in the C++ community at large.

Is this leading to faster code ?

The obvious issue is the lack of information. std::error_code is just a number and a  message. A short message that can not be changed at run-time. Exception can carry a longer descriptive text, also made at run-time.

To solve this seems not to be a problem. Use the logging, as ever before.

Make the std::error_code, log the message that explains why was it made and just then pass the std::error_code out or back or “up stream”.

This concept must yield smaller and faster executable’s. And, improve the resilience of your code.

Very often, having exceptions in use, makes you lazy to check the error’s from all sorts of API’s you use.

Recap

Make the error code, log the reason for making it and then return it.  Following this concept,  you will have to check them error codes and act accordingly.

Nobody else will do it, there are no exceptions flying above your code.

Throw only if you really have to. Sometimes it is not logical or not possible not to throw. Fine, do it. But throw the same std::error_code you prepared as above.

Enjoy the standard C++.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.