C++ Exception Handling
Exception handling is a mechanism in C++ that allows you to handle runtime errors so that the normal flow of the program can be maintained. It provides a way to transfer control from one part of the program to another in case of an exception.
Key Topics
1. Try-Catch Blocks
The try-catch block is used to enclose the code that might throw an exception. The catch block is used to handle the exception.
Example: Try-Catch Block
try {
// Code that might throw an exception
int x = 5 / 0;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
Code Explanation: The try block contains code that might throw an exception. The catch block catches the exception and handles it by printing an error message.
2. Throwing Exceptions
Exceptions can be thrown using the throw keyword. This is typically done when a function encounters an error that it cannot handle.
Example: Throwing an Exception
void divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero");
}
std::cout << "Result: " << a / b << std::endl;
}
Code Explanation: The divide function throws a runtime_error exception when the divisor is zero.
3. Custom Exceptions
Custom exceptions can be created by deriving a class from the std::exception class.
Example: Custom Exception
class DivideByZeroException : public std::exception {
public:
const char* what() const throw() {
return "Division by zero";
}
};
Code Explanation: The DivideByZeroException class is a custom exception that inherits from std::exception. It overrides the what() method to provide a custom error message.
Key Takeaways
- Exception handling is a mechanism to handle runtime errors in C++.
- Try-catch blocks are used to enclose code that might throw an exception and handle it.
- Exceptions can be thrown using the throw keyword.
- Custom exceptions can be created by deriving a class from the std::exception class.