C++•Error Handling
C++ Exception Handling: try, catch, and std::exception
Learn C++ exception semantics, deriving custom exceptions from std::exception, and RAII stack unwinding.
Syntax
try {
throw std::runtime_error("message");
} catch (const std::exception& e) {
std::cerr << e.what();
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| throw | Statement | Raises an exception object. |
| catch (const std::exception& e) | Handler | Catches exception by reference to preserve polymorphism. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C++ locally:
#include <iostream>
#include <stdexcept>
#include <string>
double safeDivide(double a, double b) {
if (b == 0.0) {
throw std::invalid_argument("Division by zero is undefined in arithmetic.");
}
return a / b;
}
int main() {
std::cout << "--- Testing Exception Handling ---\n";
try {
std::cout << "100 / 4 = " << safeDivide(100.0, 4.0) << "\n";
std::cout << "Attempting 50 / 0...\n";
double fail = safeDivide(50.0, 0.0);
std::cout << "Result: " << fail << "\n";
} catch (const std::invalid_argument& err) {
std::cout << "[CAUGHT] Invalid Argument: " << err.what() << "\n";
} catch (const std::exception& err) {
std::cout << "[CAUGHT] Standard Exception: " << err.what() << "\n";
}
std::cout << "Program recovered cleanly without crashing.\n";
return 0;
}Expected Output:
--- Testing Exception Handling --- 100 / 4 = 25 Attempting 50 / 0... [CAUGHT] Invalid Argument: Division by zero is undefined in arithmetic. Program recovered cleanly without crashing.
How It Works: Step-by-Step
- Lines 5-10: Validates denominator and throws std::invalid_argument on zero.
- Lines 15-24: Monitors operations in try block and catches exception by const reference.
Key Concepts
- Always catch exceptions by const reference (const std::exception& e) to avoid object slicing.
- C++ cleans up local stack objects automatically during stack unwinding.
- Use exceptions for exceptional conditions, not everyday control flow.
Common Mistake: Catching exceptions by value instead of const reference
Catching by value slices derived exception objects, losing custom messages and types.
❌ Incorrect
catch (std::exception e) { /* Slices object! */ }✅ Correct
catch (const std::exception& e) { /* Preserves full exception type */ }Related C++ Tutorials & Compiler
C++ Smart Pointers and RAII Memory Management (C++11)
Master modern C++ memory management using std::unique_ptr, std::shared_ptr, and RAII.
C++ Classes and Object-Oriented Programming (OOP)
Construct object blueprints with public/private access specifiers, constructors, and destructors.
C++ Functions: Pass-by-Value, Pass-by-Reference, and Const
Understand function parameters, pass-by-value vs pass-by-reference (&), and const correctness.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.