C++ exception handling
Created By: chatGPT
Exception handling in C++ is a powerful feature that allows developers to manage runtime errors gracefully. Instead of crashing the program, you can use exceptions to control the flow of the program when an unexpected situation occurs. To implement exception handling, you typically use three keywords:
try
, catch
, and throw
. Here's how it works:try {
// Code that may throw an exception
if (someErrorCondition) {
throw std::runtime_error("An error occurred");
}
} catch (const std::runtime_error& e) {
// Handle the exception
std::cout << "Caught an exception: " << e.what() << std::endl;
}
You start with a
try
block that contains code that might throw an exception. When an exception occurs, the code in the try
block is terminated, and control is passed to the catch
block. The catch
block specifies how to handle a particular type of exception. You can use multiple catch
blocks to handle different exceptions.try {
// Code that may throw multiple types of exceptions
} catch (const std::runtime_error& e) {
std::cout << "Runtime error: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cout << "General exception: " << e.what() << std::endl;
}
Sometimes, you might want to create custom exceptions for specific error handling. You can do this by inheriting from the standard
std::exception
class. This allows you to create more meaningful error messages and categorize exceptions as needed.class MyCustomException : public std::exception {
public:
virtual const char* what() const throw() {
return "My custom exception occurred";
}
};
try {
throw MyCustomException();
} catch (const MyCustomException& e) {
std::cout << e.what() << std::endl;
}
It's also essential to ensure that resources are properly managed when exceptions occur. Using RAII (Resource Acquisition Is Initialization) principles helps in managing resources effectively, ensuring that objects are destroyed when they go out of scope, even during exceptional circumstances. Here's an example of how you might manage resources safely:
class Resource {
public:
Resource() { std::cout << "Resource acquired" << std::endl; }
~Resource() { std::cout << "Resource released" << std::endl; }
};
try {
Resource res;
// Simulate an error
throw std::runtime_error("Error occurred");
} catch (...) {
std::cout << "Caught an exception" << std::endl;
}