Exceptions
In C++, exceptions provide a way to handle errors and exceptional conditions that may occur during the execution of a program. Exceptions allow you to separate error-handling code from the normal flow of control, making your code cleaner and more maintainable.
Here’s how exceptions work in C++:
- Throwing Exceptions: When a problem occurs during the execution of a program, you can “throw” an exception using the
throw
keyword. This can be done anywhere in your code, typically inside a function.
void someFunction() {
// Something went wrong
throw SomeException("An error occurred");
}
2. Catching Exceptions: When you throw an exception, you can catch it using a try
block. The try
block is followed by one or more catch
blocks that handle different types of exceptions.
try {
someFunction();
} catch (const SomeException& e) {
// Handle the exception
std::cerr << "Exception caught: " << e.what() << std::endl;
}
3. Standard Exceptions: C++ provides a set of standard exception classes defined in the <stdexcept>
header. These include std::exception
as the base class and derived classes like std::runtime_error
, std::logic_error
, and others.
#include <stdexcept>
void someFunction() {
if (/* some condition */) {
throw std::runtime_error("An error occurred");
}
}
4. Custom Exceptions: You can define your own exception classes by inheriting from std::exception
or any of its derived classes. This allows you to create exceptions specific to your application.
#include <stdexcept>
class MyException : public std::runtime_error {
public:
MyException(const std::string& message)
: std::runtime_error(message) {}
};
5. Clean-up with RAII: Resource Acquisition Is Initialization (RAII) is a C++ programming idiom where resource management is tied to object lifetime. RAII helps manage resources such as memory, file handles, and network connections automatically. By using RAII, you can ensure that resources are properly released, even in the presence of exceptions.
#include <iostream>
#include <fstream>
int main() {
std::ofstream file("example.txt");
if (!file.is_open()) {
throw std::runtime_error("Failed to open file");
}
file << "Hello, World!" << std::endl;
return 0; // file will be closed automatically when 'file' goes out of scope
}
Overall, exceptions provide a powerful mechanism for handling errors and exceptional conditions in C++, helping to improve the robustness and reliability of your code.