In this chapter, we will learn some advanced C++ exception handling techniques. We assume here that you have a basic understanding of how to throw as well as catch a C++ exception. Instead of focusing on the basics of C++ exceptions, this chapter will teach you some of the more advanced techniques of C++ exception handling. This includes the proper use of the noexcept specifier and the noexcept operator so that you can properly mark your APIs as either possibly throwing an exception or explicitly not throwing a C++ exception, instead of calling std::terminate() when an error occurs that cannot be handled.
This chapter will also explain what the term Resource Acquisition is Initialization (RAII) is and how it complements C++ exception handling. We will also discuss why you should never throw a C++ exception from a class's destructor and how to handle these types of issues. Finally, we will look at how to create your own custom C++ exceptions including providing some basic guidelines on what to do and what not to do when creating your own exceptions.
From the information provided in this chapter, you will gain a better understanding of how C++ exceptions work under the hood and the types of things that can be done with C++ exceptions to build more robust and reliable C++ programs.
The recipes in this chapter are as follows:
- Using the noexcept specifier
- Using the noexcept operator
- Using RAII
- Learning why to never throw exceptions in destructors
- Easily creating your own exception classes