In C++, exceptions are a mechanism for handling error conditions in a controlled way. When an exception is thrown, the normal flow of a program is interrupted, and control is transferred to the nearest handler for the type of exception thrown.
To use exceptions, you can follow these steps:
-
Throw an Exception: Use the throw keyword followed by an exception object when an error condition occurs. This can be a standard exception from the <stdexcept> header or a custom exception class derived from std::exception.
-
Catch an Exception: Use the try block to wrap the code that may throw an exception, and follow it with one or more catch blocks to handle specific exceptions.
-
Handle the Exception: In the catch block, write code to handle the error, such as cleaning up resources, providing error messages, or attempting an alternative approach.
Here is an example of a function that throws an exception and the corresponding code to catch any exception:
#include <iostream>
#include <stdexcept> // For standard exception classes
// Example function that might throw an exception
void riskyFunction() {
// Some code that might throw an exception
throw std::runtime_error("A runtime error has occurred!");
}
int main() {
try {
riskyFunction(); // Call the function that may throw an exception
} catch (const std::exception& e) {
// Catch any exception derived from std::exception
std::cerr << "Caught an exception: " << e.what() << std::endl;
} catch (...) {
// Catch any other types of exceptions
std::cerr << "Caught an unknown exception." << std::endl;
}
// Rest of your code...
return 0;
}
In the above code:
- We have defined a function
riskyFunction() that throws a std::runtime_error exception.
- In the
main() function, we have a try block that calls riskyFunction().
- The first
catch block is designed to catch any exception that is derived from the std::exception class. It uses the exception's what() member function to output the error message.
- The second
catch block, which uses the ellipsis (...), is a catch-all handler that will catch any exception not caught by the preceding catch blocks. This includes exceptions not derived from std::exception.
Note that catching all exceptions using catch (...) is generally discouraged unless you're re-throwing the exception or in certain cases where you must guarantee that no exceptions escape (for example, in a destructor). It is often better to catch specific exceptions so that you can handle each type appropriately.