Untitled

mail@pastecode.io avatar
unknown
plain_text
13 days ago
736 B
2
Indexable
Never
#include <iostream>
#include <stdexcept>

int getFromArray(int index) {
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    if (index < 0 || index >= 10) {
        throw std::out_of_range("Index out of range: " + std::to_string(index));
    }

    return arr[index];
}

int main() {
    try {
        int val1 = getFromArray(5);
        std::cout << "Value at index 5: " << val1 << std::endl;

        int val2 = getFromArray(-1);
        std::cout << "Value at index -1: " << val2 << std::endl;

        int val3 = getFromArray(20);
        std::cout << "Value at index 20: " << val3 << std::endl;
    } catch (const std::out_of_range& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}
Leave a Comment