As you know from Section 7.10, an exception is an indication of a problem that occurs during a program’s execution. Exception handling enables you to create applications that can resolve (or handle) exceptions. In many cases, this allows a program to continue executing as if no problem had been encountered. The features presented in this chapter enable you to write robust and fault-tolerant programs that can deal with problems and continue executing or terminate gracefully.
We begin with a review of exception-handling concepts via an example that demonstrates handling an exception that occurs when a function attempts to divide by zero. We show how to handle exceptions that occur in a constructor or destructor and exceptions that occur if operator new
fails to allocate memory for an object. We introduce several C++ Standard Library exception handling classes and show you how to create your own.
Software Engineering Observation 17.1
Exception handling provides a standard mechanism for processing errors. This is especially important when working on a project with a large team of programmers.
Software Engineering Observation 17.2
Incorporate your exception-handling strategy into your system from its inception. Including effective exception handling after a system has been implemented can be difficult.
Error-Prevention Tip 17.1
Without exception handling, it’s common for a function to calculate and return a value on success or return an error indicator on failure. A common problem with this achitecture is using the return value in a subsequent calculation without first checking whether the value is the error indicator. Exception handling eliminates this problem.