┌───────────────────┐
│ std::exception │
└─────────┬─────────┘
┌──────────────┴──────────────┐
┌────────┴────────┐ ┌────────┴────────┐
│ std::runtime_ │ │ std::logic_ │
│ error │ │ error │
└────────┬────────┘ └────────┬────────┘
┌──────┴──────┐ ┌──────┴──────┐
│ overflow_ │ │ invalid_ │
│ error │ │ argument │
│ out_of_range│ │ out_of_range│
└─────────────┘ └─────────────┘ Topic 66 of 91 9. C++ Standard Template Library (STL) Interactive Tutorial
Exception Handling in C++: Detecting and Managing Runtime Failures
On This Page0 sectionsQuick jump to subtopic
Direct Answer & Core Concept
C++ exception handling provides structured error recovery using try blocks to enclose risk-prone code, throw statements to signal anomalies, and catch blocks to intercept and handle specific exception types. The standard exception hierarchy is rooted at std::exception in ``.
Detailed Explanation & Mechanics
1. Standard Exception Hierarchy:
Architecture Diagram
2. Catching by Reference:
Exceptions should always be caught by const std::exception& to avoid slicing derived exception data.
Runnable Code Example: Exception Handling in C++
C++20 / C++23main.cpp
#include <iostream>
#include <stdexcept>
#include <vector>
double divideValues(double numerator, double denominator) {
if (denominator == 0.0) {
throw std::invalid_argument("Division by zero error!");
}
return numerator / denominator;
}
int main() {
try {
double result = divideValues(100.0, 0.0);
std::cout << "Result: " << result << "\n";
}
catch (const std::invalid_argument& ex) {
std::cerr << "[Caught Argument Error]: " << ex.what() << "\n";
}
catch (const std::exception& ex) {
std::cerr << "[Caught Generic Exception]: " << ex.what() << "\n";
}
catch (...) {
std::cerr << "[Caught Unknown Exception]\n";
}
std::cout << "Application recovered and continued execution.\n";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ
Q: Why should exceptions always be caught by const reference (`catch (const std::exception& e)`)?
A: Catching by reference avoids object slicing (which would strip derived exception details) and eliminates redundant copy construction overhead.
Q
Q: What happens if an unhandled exception propagates out of `main()`?
A: `std::terminate()` is invoked, immediately aborting the process and potentially failing to execute destructors for active stack frames.
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
• Catch exceptions by
• Use standard exception classes (
• Never throw exceptions from inside destructors; mark destructors
const std::exception& to prevent object slicing.• Use standard exception classes (
std::runtime_error, std::invalid_argument) rather than throwing primitive types (e.g. throw 404;).• Never throw exceptions from inside destructors; mark destructors
noexcept.