C++ Exceptions
Throw an exception with throw and handle it with try / catch.
ExampleC++
#include <iostream>
#include <stdexcept>
using namespace std;
int divide(int a, int b) {
if (b == 0) throw runtime_error("Cannot divide by zero");
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(1, 0) << endl;
} catch (const exception &e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}Output
5 Error: Cannot divide by zero
Quick check
Which keyword raises an exception?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.