Exception Handling in C++ - A Simple Guide
Exception handling is a crucial feature in C++ that allows you to handle unexpected situations, errors, and exceptional conditions in your code gracefully. It helps you write more robust and reliable programs. In this guide, we'll explore the basics of exception handling in C++.
Try-Catch Blocks
The core of exception handling in C++ is the use of try-catch blocks. In a try block, you enclose the code that might throw an exception, and in a catch block, you specify how to handle the exception:
#include <iostream>
using namespace std;
int main() {
try {
int numerator = 10;
int denominator = 0;
if (denominator == 0) {
throw runtime_error("Division by zero is not allowed.");
}
int result = numerator / denominator;
cout << "Result: " << result << endl;
} catch (const runtime_error &e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
In this example, we use a try block to perform division and catch any exceptions thrown. If an exception is thrown, the catch block will handle it and display an error message.
Types of Exceptions
C++ allows you to define custom exception types by deriving from the standard exception classes. Common exception classes include std::exception
, std::runtime_error
, and std::logic_error
:
#include <iostream>
#include <stdexcept>
using namespace std;
class MyException : public runtime_error {
public:
MyException() : runtime_error("Custom exception") {}
};
int main() {
try {
throw MyException();
} catch (const exception &e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}
In this example, we define a custom exception class MyException
that inherits from std::runtime_error
.
Multiple Catch Blocks
You can use multiple catch blocks to handle different types of exceptions. C++ will execute the appropriate catch block based on the type of the thrown exception:
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
try {
// Code that might throw exceptions
} catch (const runtime_error &e) {
cerr << "Runtime Error: " << e.what() << endl;
} catch (const logic_error &e) {
cerr << "Logic Error: " << e.what() << endl;
} catch (const exception &e) {
cerr << "Generic Exception: " << e.what() << endl;
}
return 0;
}
Conclusion
Exception handling is a crucial part of C++ programming, enabling you to deal with errors and exceptional situations in a structured way. As you continue your C++ journey, you'll explore more advanced exception handling techniques and best practices.