- In C++ exception handling is a process to handle runtime errors.
- If we perform exception handling, so the normal flow of the application can be maintained even after runtime errors.
- At run time exception is an event or object which is thrown in C++ and all exceptions are derived from std::exception class.
- It prints exception message and terminates the program, if we don’t handle the exception.
- In C++ exception handling consists of three keywords, they are try, throw, catch
- In exception handling try keyword allows you to define a block of code to be tested for errors when it is being executed.
- In exception handling throw keyword throws an exception when a problem is detected, which lets us create a custom error.
- In exception handling catch keyword allows you to define a block of code to be executed, if an error occurs in the try block.
Syntax
try {
// Block of code to try
throw exception; // Throw an exception when a problem arise
}
catch () {
// Block of code to handle errors
}
Sample Code
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;
}
Output
