Write a function getElement(int arr[], int size, int index) that throws out_of_range if index is invalid, and returns the element otherwise. Test with valid and invalid indices.
Show Solution
#include <iostream>
#include <stdexcept>
using namespace std;
int getElement(int arr[], int size, int index) {
if (index < 0 || index >= size)
throw out_of_range("Index out of bounds: " + to_string(index));
return arr[index];
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
try {
cout << getElement(arr, 5, 2) << endl; // 30
cout << getElement(arr, 5, 10) << endl; // throws
} catch (const out_of_range& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}
Quiz
Which block contains code that might throw an exception?
A) catch
B> throw
C) try
D> handle
Answer
C) try
What does catch (...) catch?
A) Only standard exceptions
B> Only runtime_error
C) Any exception of any type
D) Nothing
Answer
C)catch (...) is a catch-all handler for any exception type.
Summary
throw raises an exception; try wraps risky code; catch handles it.
Catch by const reference for efficiency.
Use catch (...) as a fallback for unknown exceptions.
Create custom exceptions by inheriting from std::exception.