When the program calls vector
member function at
with the argument 15
(line 80), the function attempts to access the element at location 15, which is outside the vector
’s bounds—integers1
has only 10 elements at this point. Because bounds checking is performed at execution time, vector
member function at
generates an exception—specifically line 80 throws an out_of_range exception (from header <stdexcept>
) to notify the program of this problem. At this point, the try
block terminates immediately and the catch
block begins executing—if you declared any variables in the try
block, they’re now out of scope and are not accessible in the catch
block.
The catch
block declares a type (out_of_range
) and an exception parameter (ex
) that it receives as a reference. The catch
block can handle exceptions of the specified type. Inside the block, you can use the parameter’s identifier to interact with a caught exception object.