example3_bounds_checking.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
#include <iostream>
#include <array>
#include <stdexcept>

int main() {
    std::array<int, 3> arr = {1, 2, 3};

    try {
        std::cout << arr.at(2) << std::endl; // OK
        std::cout << arr.at(3) << std::endl; // Throws out_of_range
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of Range error: " << e.what() << std::endl;
    }

    return 0;
}
Back to array