try
Blocks and Exception HandlingExceptions are run-time anomalies—such as losing a database connection or encountering unexpected input—that exist outside the normal functioning of a program. Dealing with anomalous behavior can be one of the most difficult parts of designing any system.
Exception handling is generally used when one part of a program detects a problem that it cannot resolve and the problem is such that the detecting part of the program cannot continue. In such cases, the detecting part needs a way to signal that something happened and that it cannot continue. Moreover, the detecting part needs a way to signal the problem without knowing what part of the program will deal with the exceptional condition. Having signaled what happened, the detecting part stops processing.
A program that contains code that might raise an exception (usually) has another part to handle whatever happened. For example, if the problem is invalid input, the handling part might ask the user to provide correct input. If the database was lost, the handling part might alert an operator.
Exception handling supports this cooperation between the detecting and handling parts of a program. In C++, exception handling involves
• throw
expressions, which the detecting part uses to indicate that it encountered something it can’t handle. We say that a throw
raises an exception.
• try
blocks, which the handling part uses to deal with an exception. A try
block starts with the keyword try
and ends with one or more catch
clauses. Exceptions thrown from code executed inside a try
block are usually handled by one of the catch
clauses. Because they “handle” the exception, catch
clauses are also known as exception handlers.
• A set of exception
classes that are used to pass information about what happened between a throw
and an associated catch
.
In the remainder of this section, we’ll introduce these three components of exception handling. We’ll also have more to say about exceptions in § 18.1 (p. 772).