#include<iostream> #include<stdexcept> #include<vector> using namespace std; int getValue (const vector<int>& arr, int idx) { if(idx< 0 || idx>= arr.size()) { throw out_of_range("Index out of range"); } return arr[idx]; } int main() { int n;int idx; cin>>n; vector<int> arr(n); for (int i =0;i<n;i++) { cin>>arr[i]; } cin>>idx; try { int value = getValue(arr, idx) cout<<"Value: "<<value<<endl; } catch(const out_of_range& e) { cout<<"Error: "<<e.what()<<endl; } }
Test Cases
Test Results
Input
5 10 20 30 40 50 2
Expected Output
Value: 30