Exception handling in C++ is a mechanism that allows programs to manage runtime errors, maintain the normal flow of execution, and avoid program crashes. By using exception handling, you can deal with unexpected situations gracefully and ensure that your program continues running or exits cleanly.
1. Exception: An exception is an object or an event that is thrown when a runtime error occurs. All exceptions in C++ are derived from the std::exception class. If an exception is not handled, it will print an error message and terminate the program.
2. Exception Hierarchy: All standard C++ exceptions are derived from the std::exception class.
| Exception | Description |
|---|---|
| std::exception | Base class for all standard C++ exceptions. |
| std::logic_error | Indicates errors that are detected by the logic of the program. |
| std::runtime_error | Indicates errors that occur at runtime and cannot be detected beforehand. |
| std::bad_exception | Used to handle unexpected exceptions. |
| std::bad_cast | Thrown by dynamic_cast when a cast fails. |
| std::bad_typeid | Thrown by typeid when an invalid type ID is used. |
| std::bad_alloc | Thrown by new when memory allocation fails. |
In C++, there are three primary keywords used for exception handling:
1. try - Used to start a block of code that will be tested for exceptions.
2. catch - Used to define a block of code that will handle exceptions thrown by the try block.
3. throw - Used to signal that an exception has occurred and to pass it to the catch block.
<#include <iostream>>
<#include <stdexcept> // For std::runtime_error
using namespace std;
void mightGoWrong() {
bool errorOccurred = true; // Simulate an error
if (errorOccurred) {
throw runtime_error("Something went wrong");
}
}
int main() {
try {
mightGoWrong();
} catch (const runtime_error& e) {
cout << "Caught an exception: " <<
e.what() << std::endl;
} catch (...) {
cout << "Caught an unknown exception" <<
std::endl;
}
cout << "Program continues after exception handling." <<
std::endl;
return 0;
}
1. try Block: Contains code that might throw an exception. In this example, the mightGoWrong() function is called, which throws a runtime_error if an error occurs.
2. catch Block: Handles the exception thrown by the try block. In this example, it catches runtime_error exceptions and prints the error message.
3. throw Statement: Used within the mightGoWrong() function to signal that an error has occurred. It passes the exception to the nearest catch block.
1. Maintains Normal Flow: Exception handling ensures that the rest of the code continues executing even if an error occurs.
2. Improves Code Readability: Separates error handling code from regular code, making it easier to read and maintain.
3. Centralized Error Handling: Provides a centralized way to handle errors, which helps in managing complex systems more effectively.
4. Robustness: Helps in creating more robust applications by handling unexpected conditions gracefully.
Exception handling is an essential feature in C++ for writing reliable and maintainable code. It allows you to manage errors effectively, ensuring that your programs can handle and recover from unexpected situations.