Exceptions
throw raises an exception and catch handles it. Catch by const reference. The standard library has exceptions such as invalid_argument and out_of_range, and vector::at throws on a bad index.
Example
#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;
int divide(int a, int b) {
if (b == 0) throw invalid_argument("divide by zero");
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(1, 0) << endl;
} catch (const exception& e) {
cout << "Caught: " << e.what() << endl;
}
vector<int> v = {1, 2};
try { v.at(5); } catch (const out_of_range&) { cout << "bad index" << endl; }
}Result
5 Caught: divide by zero bad index
Exercise
Raise an error.
runtime_error("oops");Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.