#include <stdexcept>
double divide(double a, double b) {
if (b == 0) throw runtime_error("Division by zero!");
return a / b;
}
try {
cout << divide(10, 2); // 5
cout << divide(10, 0); // throws!
} catch (const runtime_error& e) {
cerr << "Error: " << e.what() << endl;
}
// Program continues after the catch block
try {
// ...
} catch (const out_of_range& e) {
// handle specific case
} catch (const runtime_error& e) {
// handle runtime errors
} catch (...) {
// catch everything else
}
When an exception unwinds the stack, destructors run for all local objects — files close, memory frees, locks release — automatically.
Write safeAt(vector<int> v, int i) that returns v[i], but throws out_of_range("index out of range") if i is out of bounds.
Click "Run" to execute your code.