Chapter 3. Exceptions and Expectations
You can now write a short program, and you’ve started to think about potential problems with input. I showed you how to write a function returning a bool to indicate success or otherwise, but there are more refined ways of handling problems. This chapter will demonstrate two approaches: exceptions and expectations. You will learn other elements of C++, getting more practice writing functions and building a deeper understanding of block scope.
C++ has supported exceptions for a long time, but some people writing embedded code prefer not to use them because they have an overhead.
C++23 introduced a new type called std::expected, which holds either a return value or an error. I will show you both approaches in this chapter, and then you’ll be ready to build a larger program in Chapter 4.
Exceptions
Most languages provide a way to raise an exception if a problem happens and provide ways to handle the situation.
As with other programming languages, if you try a statement that raises an exception, the program jumps to another location.
Being able to jump out of a function or to another place if something goes wrong might seem like magic.
The specifics of how exceptions work vary between toolchains, but jumping elsewhere needs some extra housekeeping.
You can specify a function as noexcept to declare that it will not throw exceptions, which allows the toolchain to avoid some overhead.
You’ll see some examples of noexcept later in Chapter 11.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access