C++:C++ Exception Handling: try, catch, and std::exception
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:

ParameterTypeDescription
throwStatementRaises an exception object.
catch (const std::exception& e)HandlerCatches exception by reference to preserve polymorphism.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler