To handle an exception, place any code that might throw an exception in a try statement (lines 77–85). The try block (lines 77–81) contains the code that might throw an exception, and the catch block (lines 82–85) contains the code that handles the exception if one occurs. As you’ll see in Chapter 17, you can have many catch
blocks to handle different types of exceptions that might be thrown in the corresponding try
block. If the code in the try
block executes successfully, lines 82–85 are ignored. The braces that delimit try
and catch
blocks’ bodies are required.
The vector
member function at provides bounds checking and throws an exception if its argument is an invalid subscript. By default, this causes a C++ program to terminate. If the subscript is valid, function at
returns the element at the specified location as a modifiable lvalue or a nonmodifiable lvalue. A nonmodifiable lvalue is an expression that identifies an object in memory (such as an element in a vector
), but cannot be used to modify that object. If at
is called on a const array
or via a reference that’s declared const
, the function returns a nonmodifiable lvalue.
18.216.42.251