C++ catch Keyword
Example
Use try catch
for handling errors:
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 catch
keyword catches exceptions generated by a try
statement.
The catch statement allows you to define a block of code to be executed if an exception is thrown in the try block. In the catch block a variable containing the exception is available.
Syntax
catch(exceptionType exception) { code block }
exceptionType is the data type of an exception thrown by a try
block. exception contains the exception that was thrown. Code written in the code block will be executed if an exception is caught.
Related Pages
The throw
keyword creates exceptions.
The try
keyword specifies the block of code from which the exceptions are caught.
Read more about exceptions in our C++ Exceptions Tutorial.