bhylu.com

Advertisements

C++ Exceptions

Throw a meaningful domain error, catch it by const reference and leave resource cleanup to owners.

How it works

An exception transfers control to a matching handler while automatic objects in exited scopes are destroyed. Throw when an operation cannot fulfil its contract and the chosen interface uses exceptions for that failure. Catch standard exception types by const reference to avoid slicing. Ordinary absence can be better represented by optional; do not throw merely because a search found no match. A useful boundary translates failure into a clear message or status without silently continuing as though the operation succeeded.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror exceptions.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · exceptions.cpp

#include <iostream>
#include <stdexcept>

int capacity_for(int requested) {
    if (requested <= 0) { throw std::invalid_argument{"positive capacity required"}; }
    return requested;
}

int main() {
    try {
        int capacity = capacity_for(-2);
        std::cout << "Capacity: " << capacity << '\n';
    } catch (const std::invalid_argument& error) {
        std::cout << "Rejected: " << error.what() << '\n';
    }
}

Expected result

Rejected: positive capacity required

The potentially failing operation happens before a success label is written. The negative request throws and the matching handler explains its rejection without a partial success message. Stack unwinding releases standard owners, but an operation that partly changed external state may still need transaction-like design. Catch only where you can recover or translate the failure meaningfully.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.