Exception Handling: try, catch, throw, and std::exception
Exceptions separate error detection from error resolution, preventing system crashes when bad inputs occur.
What is it?
C++ exception handling uses `try`, `catch`, and `throw`. Standard exceptions derive from the `std::exception` base class defined in `<stdexcept>`.
Why is it used?
Gracefully recovers from out-of-memory errors, invalid array indices, and file opening failures.
Detailed Explanation
Standard Exception Hierarchy:
• `std::exception`: Root class.
• `std::runtime_error`: Errors detected during execution.
• `std::invalid_argument`: Invalid parameters.
• `std::out_of_range`: Index boundary violations (thrown by `std::vector::at()`).
• Catching by Reference: Always catch exceptions by `const std::exception &e` to prevent object slicing!
Syntax Structure
Syntax Blueprint
try {
throw std::runtime_error("Error details");
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
}
Code Example
CPP Code
#include <iostream>
#include <stdexcept>
#include <string>
// Safe Tuition Calculator with Exception Throwing
double calculate_discounted_fee(double base_fee, double discount_pct) {
if (base_fee < 0) {
throw std::invalid_argument("Base fee cannot be negative.");
}
if (discount_pct < 0 || discount_pct > 100) {
throw std::out_of_range("Discount percentage must be between 0 and 100.");
}
return base_fee - (base_fee * (discount_pct / 100.0));
}
int main() {
std::cout << "=== Exception Handling Demonstration ===\n";
// Test valid calculation
try {
double fee = calculate_discounted_fee(2500, 10);
std::cout << "[SUCCESS] Calculated Fee: ₹" << fee << "\n";
} catch (const std::exception &e) {
std::cerr << "[CAUGHT] " << e.what() << "\n";
}
// Test invalid discount throwing exception
try {
double fee = calculate_discounted_fee(2500, 150); // Invalid 150% discount!
} catch (const std::exception &e) {
std::cerr << "[CAUGHT] Exception Intercepted: " << e.what() << "\n";
}
return 0;
}
Explanation of the Code
• `throw std::out_of_range(...)` halts invalid execution.
• `catch (const std::exception &e)` intercepts the exception safely.
• `e.what()` returns the descriptive error message.
Expected Output
=== Exception Handling Demonstration ===
[SUCCESS] Calculated Fee: ₹2250
[CAUGHT] Exception Intercepted: Discount percentage must be between 0 and 100.
Real-World Application
Used across server request routers, audio/video file decoders, and database query drivers.
Common Mistakes to Avoid
• Catching exceptions by value `catch (std::exception e)` (causes object slicing).
• Throwing exceptions inside destructors (if an exception escapes a destructor during stack unwinding, `std::terminate()` aborts the program immediately!).
Quick Practice Challenge
Throw a `std::runtime_error` when a divisor is 0 in a division function.
Key Takeaways
• Throw standard exceptions from `<stdexcept>`.
• Always catch by `const std::exception &e`.
• Never allow exceptions to escape destructors.