Exception handling is a programming language construct that helps manage runtime errors by:
- Separating error handling code from normal code
- Allowing errors to be propagated up the call stack
- Providing a structured way to detect and handle runtime errors
try {
// Code that might throw an exception
} catch (const std::exception& e) {
// Code to handle the exception
}try: Contains code that might throw an exceptioncatch: Handles specific types of exceptions- Multiple catch blocks can handle different exception types
std::exception: Base class for all standard exceptions- Custom exceptions should inherit from std::exception
- Virtual
what()function provides error description
Custom exceptions allow for:
- Domain-specific error handling
- Meaningful error messages
- Type-based exception handling
Basic structure:
class MyException : public std::exception {
public:
virtual const char* what() const throw() {
return "My error message";
}
};A class must provide four essential functions:
- Default constructor
- Copy constructor
- Copy assignment operator
- Destructor
Purpose:
- Ensures proper object creation, copying, and cleanup
- Prevents memory leaks
- Enables proper object management
- Functions marked with
constafter parameter list - Promise not to modify object's state
- Can be called on const objects
- Example:
int getValue() const;
- Members declared with
constcannot be modified - Must be initialized in constructor initialization list
- Common for immutable properties of a class
Three levels of access:
public: Accessible from anywhereprivate: Only accessible within the classprotected: Accessible in class and derived classes
- Allows custom output formatting for objects
- Usually implemented as a non-member function
- Takes stream and object as parameters
std::ostream& operator<<(std::ostream& os, const Class& obj);