C++ try 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 try
keyword creates a try...catch statement.
The try
statement allows you to define a block of code to be tested for errors while it is being executed.
The catch
statement allows you to define a block of code to be executed, if an error occurs in the try block.
Related Pages
The catch
keyword runs code when an exception is thrown.
The throw
keyword creates exceptions.
Read more about exceptions in our C++ Exceptions Tutorial.