C++ Exception Handling
Exception handling in C++ is a mechanism that allows you to gracefully handle and recover from runtime errors or exceptional conditions that can occur during the execution of your program. It provides a way to separate error-handling code from the normal flow of your program, improving code readability and robustness.
Here are the key components and concepts related to exception handling in C++:
- Throwing an Exception: You can throw an exception using the
throw
keyword. Exceptions can be of various types, including built-in types like integers and strings, or user-defined types derived from thestd::exception
class.
throw 42; // Throw an integer exception
throw "An error occurred"; // Throw a C-style string exception
throw std::runtime_error("Custom exception message"); // Throw an exception of a specific type
- Catching an Exception: You catch exceptions using the
try
andcatch
blocks. Thetry
block contains the code that may throw an exception, and thecatch
block(s) handle specific types of exceptions.
try {
// Code that may throw an exception
}
catch (int e) {
// Handle integer exceptions
}
catch (const char* e) {
// Handle C-style string exceptions
}
catch (std::exception& e) {
// Handle exceptions of a specific type
}
catch (...) {
// Handle all other exceptions (catch-all)
}
You can have multiple catch
blocks to handle different types of exceptions, and they are checked in order from top to bottom. The first matching catch
block will be executed.
- Exception Classes: C++ provides a hierarchy of exception classes, including
std::exception
and its derived classes, which are designed for specific types of exceptions. You can also create your custom exception classes by inheriting fromstd::exception
or its subclasses.
#include <stdexcept>
try {
// Code that may throw an exception
}
catch (const std::runtime_error& e) {
// Handle runtime_error exceptions
}
- Rethrowing Exceptions: You can rethrow an exception from within a
catch
block to allow it to be caught by an outertry-catch
block or to propagate it up the call stack.
try {
try {
throw std::runtime_error("Inner exception");
}
catch (const std::exception& e) {
// Handle inner exception
throw; // Rethrow the same exception
}
}
catch (const std::exception& e) {
// Handle the rethrown exception at the outer level
}
- Custom Exception Classes: You can define your own exception classes by deriving from
std::exception
or its subclasses. This allows you to create custom exception types with meaningful error messages and additional data.
class MyException : public std::exception {
public:
MyException(const char* message) : message_(message) {}
const char* what() const noexcept override {
return message_.c_str();
}
private:
std::string message_;
};
- Handling Resource Management: Exception handling is essential for managing resources like memory, files, and network connections. By using RAII (Resource Acquisition Is Initialization) and smart pointers, you can ensure that resources are properly released when exceptions are thrown.
#include <iostream>
#include <memory>
void manipulateResource() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
// Manipulate the resource
throw std::runtime_error("An error occurred");
}
int main() {
try {
manipulateResource();
}
catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
Exception handling in C++ is a powerful tool for writing reliable and robust code. It allows you to gracefully handle errors, provide meaningful error messages, and prevent your program from crashing due to unexpected conditions. Proper exception handling is an important aspect of software development for building maintainable and stable applications.