Skip to content
C++

Exception Handling

try-catch and custom exceptions.

By EZ4Code Team
exceptionexception

Code

#include <iostream>
#include <stdexcept>
#include <string>

// Custom exception
class DivisionByZero : public std::runtime_error {
public:
    DivisionByZero() : std::runtime_error("division by zero") {}
};

// Exception safety
double safe_divide(double a, double b) {
    if (b == 0) throw DivisionByZero{};
    return a / b;
}

// RAII ensures exception safety
class Resource {
public:
    Resource() { std::cout << "acquire\n"; }
    ~Resource() { std::cout << "release\n"; }
};

int main() {
    try {
        Resource r; // Released even if exception thrown
        double result = safe_divide(10, 0);
        std::cout << result << std::endl;
    } catch (const DivisionByZero& e) {
        std::cerr << "Error: " << e.what() << "\n";
    } catch (const std::exception& e) {
        std::cerr << "Std error: " << e.what() << "\n";
    } catch (...) {
        std::cerr << "Unknown error\n";
    }

    // noexcept
    auto safe_func = []() noexcept { return 42; };

    // Rethrow exception
    try {
        try {
            throw std::runtime_error("inner");
        } catch (...) {
            std::cout << "caught inner\n";
            throw; // Rethrow
        }
    } catch (const std::exception& e) {
        std::cout << "caught outer: " << e.what() << "\n";
    }

    return 0;
}

Explanation

C++ exceptions are handled via try-catch; noexcept marks functions that don't throw; RAII ensures exception safety.

More C++ Snippets