Exception handling in C++ is a mechanism to detect and handle runtime errors gracefully, without crashing the program.
An exception is an unexpected situation or error that occurs during the execution of a program (e.g., divide by zero, invalid input, out-of-range access).
Exception handling mechanism provide a way to transfer control from one part of a program to another. This makes it easy to separate the error handling code from the code written to handle the actual functionality of the program.
C++ exception handling is built upon three keywords:
try block: Code block that may cause an exception is typically placed inside the try block. It is followed by one or more catch blocks.throw keyword: Theย throwย keyword is used to throw the exception.catch block: this block catches the exception thrown from the try block. Code to handle the exception is written inside this catch block.
Syntax:
try {
throw val
}
catch (ExceptionType e) {
// exception handling code
}
There are three types of values that can be thrown as an exception: