Member-only story

Modern error handling in C++

Michał Fita
7 min readJun 7, 2021

--

To date, the most known method of handling errors in C++ is the exceptions mechanism. However, in many applications (including embedded systems) some features of exceptions are unacceptable. Rust from from start offers a mechanism based on a 2-choice variant, which is widely praised, but criticised by some. In the embedded world it’s a perfect solution. But what about C++?

Exception Handling

The software exception handling first appeared in Lisp 1.5, about 29 years before standardised in C++. They appeared in other languages before that, including Ada — a famous safe language designed for the Department of Defence. What’s interesting Tony Hoare (the author of quicksort and Hoare logic) criticised Ada’s exceptions as dangerous.

In Java, exceptions are available from the beginning and are standard pattern for error handling. Standard libraries are full of hierarchical exceptions of various kinds. What’s interesting here, is that only objects allowed to be thrown have to have java.lang.Throwable in the inheritance hierarchy. This helps to handle exceptions in a universal way using functions with identical signature to log or print out messages related to them. What’s more important, such exceptions carry information about the stack trace (quite often called backtrace these days).

Technically, exceptions in C++ lead to several problems, apart from the code blow, most important are stack unwinding and lack of type restriction — any type can be thrown as an exception. Some claim…

--

--

Michał Fita
Michał Fita

Written by Michał Fita

Software Craftsman who started programming before even had a computer.

No responses yet