Exception handling in C++
C++ exception handling is a mechanism that allows you to handle errors that occur during the execution of a program. It is built on three keywords: try, catch, and throw.
- The
try
keyword is used to define a block of code that can throw an exception. - The
catch
keyword is used to define a block of code that is executed when a particular exception is thrown. - The
throw
keyword is used to throw an exception.
The following is an example of a simple try-catch block:
int main() {
try {
// This code might throw an exception.
throw(something can be of any type)
} catch (int e) {
// This code is executed if an exception of type int is thrown.
std::cout << "An integer exception was thrown: " << e << std::endl;
} catch (std::string e) {
// This code is executed if an exception of type std::string is thrown.
std::cout << "A string exception was thrown: " << e << std::endl;
}
}
In this example, the try
block contains the code that might throw an exception. The catch
blocks are executed if a particular type of exception is thrown. In this case, there are two catch blocks: one for exceptions of type int
and one for exceptions of type std::string
.
If an exception is thrown in the try
block, the first catch
block that matches the type of the exception is executed. If no catch
block matches the type of the exception, the program terminates abnormally.
You can also have multiple catch blocks for the same type of exception. In this case, the catch blocks are executed in the order in which they appear in the code.
The throw
keyword is used to throw an exception. The syntax for the throw
keyword is:
throw expression;
The expression
can be any value. When the throw
keyword is executed, the expression
is passed to the first catch
block that matches its type.
Here is an example of a throw
statement:
throw 10;
This statement throws an exception of type int
with the value of 10.
The try
, catch
, and throw
keywords can be used to handle a wide variety of errors. For example, you can use them to handle errors that occur when opening files, reading from files, or writing to files. You can also use them to handle errors that occur when dividing by zero, accessing invalid memory, or calling a function that does not exist.