When executing C++ code, runtime errors can occur. For example, a user might enter invalid data, a file might be missing, or a calculation might attempt to divide by zero.
Instead of letting the program crash abruptly, C++ allows you to "catch" these errors and handle them gracefully using Exceptions.
Exception handling in C++ consists of three keywords: try, throw, and catch.
try: Allows you to define a block of code to be tested for errors while it is being executed.throw: When a problem is detected, you use this keyword to create a custom error (throw an exception).catch: Allows you to define a block of code to be executed if an error occurs in the try block.
try {
// Block of code to try
throw exception; // Throw an error when a problem arise
}
catch () {
// Block of code to handle errors
}
Let's look at a practical example. We want to check a user's age. If they are 18 or older, they are granted access. If they are under 18, we will throw an exception.
#include <iostream> using namespace std;int main() { try { int age = 15; if (age >= 18) { cout << "Access granted - you are old enough."; } else { // Throw an error code (we chose the integer 505) throw 505; } } catch (int myNum) { cout << "Access denied - You must be at least 18 years old.\n"; cout << "Error number: " << myNum; }
return 0; }
How it works:
try block.if statement checks the age. Because 15 is less than 18, the else block triggers.throw 505; statement immediately stops the try block and looks for a catch block that accepts integers.catch (int myNum) block takes over, printing our custom error message and the error code 505.catch (...))Sometimes, you might not know exactly what type of exception will be thrown (it could be an int, a string, or an object). If you want your catch block to handle any type of exception, use three dots ... inside the catch parentheses.
try {
int age = 15;
if (age < 18) {
throw "Not old enough!"; // Throwing a string this time
}
}
catch (...) { // Catches any type of exception
cout << "Access denied!";
}
Which keyword is used to generate a custom error in C++?