Junior
What are exceptions in C++?
sobes.tech AI
Answer from AI
Mechanism for handling abnormal situations (errors) that occur during program execution. It allows separating the code responsible for the program logic from the error handling code.
Keywords:
try: Defines a block of code where exceptions may occur.catch: Defines a block of code that executes when a specific type of exception occurs.throw: Generates (creates) an exception. The exception type can be any object.
Working principle:
- Code that may cause an error is placed in the
tryblock. - If an exception occurs in the
tryblock (generated usingthrow), the normal program execution is interrupted. - The system searches for a suitable
catchblock capable of handling the generated exception (by type). - If a matching
catchis found, its code is executed. - If no suitable
catchis found at the current call level, the exception is "propagated" up the call stack until a suitable handler function is found (or the program terminates abnormally).
Example:
#include <iostream>
#include <stdexcept> // For standard exception types
int divide(int a, int b) {
if (b == 0) {
throw std::runtime_error("Division by zero!"); // Generate an exception
}
return a / b;
}
int main() {
try {
int result = divide(10, 0); // Call a function that may throw an exception
std::cout << "Result: " << result << std::endl; // This line will not execute
} catch (const std::runtime_error& e) { // Catch exception of type std::runtime_error
std::cerr << "Error: " << e.what() << std::endl; // Handle the exception
} catch (...) { // Catch any other exception (ellipsis)
std::cerr << "An unknown error occurred." << std::endl;
}
std::cout << "Program continues after error handling." << std::endl;
return 0;
}
Advantages:
- Separation of logic from error handling.
- Simplification of the main execution flow code.
- Ability to handle errors at different levels of the call hierarchy.
Disadvantages:
- May affect performance (due to stack unwinding).
- Complexity in understanding the execution flow with multiple exceptions.
- Incorrect use can lead to resource leaks (if resources are not released when an exception occurs before their proper release).
For safe resource management in the presence of exceptions, RAII (Resource Acquisition Is Initialization) and smart pointers are often used.