Introduction

This chapter contains recipes for using C++’s exception-handling features. C++ has strong support for exception handling, and by employing a few techniques you can write code that handles exceptional circumstances effectively and is easy to debug.

The first recipe describes C++’s semantics for throwing and catching exceptions, then it explains how to write a class to represent exceptions. This is a good starting point if you have little or no experience with exceptions. It also describes the standard exception classes that are defined in <stdexcept> and <exception>.

The rest of the recipes illustrate techniques for using exceptions optimally, and they define several key terms along the way. Just throwing an exception when something unexpected happens, or catching an exception only to print an error message and abort does not make for good software. To use C++’s exception-handling facilities effectively, you have to write code that doesn’t leak resources if an exception is thrown, and that otherwise has well-defined behavior when an exception is thrown. These are known as the basic and strong exception-safety guarantees. I describe techniques you can use that allow you to make these guarantees for constructors and various member functions.

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.