C++ throw Keyword
Example
Throw an exception if age is below 18:
try {
int age = 15;
if (age >= 18) {
cout << "Access granted - you are old enough.";
} else {
throw (age);
}
}
catch (int myNum) {
cout << "Access denied - You must be at least 18 years old.\n";
cout << "Age is: " << myNum;
}
Definition and Usage
The throw
keyword is used to create a custom error.
The exception thrown by the throw
keyword can be used by code in a catch
block.
Related Pages
The catch
keyword runs code when an exception is thrown.
The try
keyword specifies a block of code from which exceptions can be caught.
Read more about exceptions in our C++ Exceptions Tutorial.