Exception handling lets you gracefully deal with error situations that can occur while a program is running. In cases like a missing file, invalid input, or dividing by zero, you can stop the whole program from crashing using try, throw, catch.
cpp
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age < 18) {
throw string("You must be at least 18 years old.");
}
cout << "Access granted.";
} catch (string message) {
cout << "Access denied: " << message;
}
return 0;
}try contains the logic that could error out. If age doesn't meet the minimum, throw fires off an error message, and catch handles it.
You should see
Access denied: You must be at least 18 years old.Info
Exceptions are meant for expected error flows. You shouldn't write every ordinary condition check as an exception.