LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 25 of 27

Exception Handling

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Exception Handling · Study material

Exception handling in C++ separates the code that detects an error from the code that knows how to deal with it. A function that cannot do its job throws an exception; control jumps out of every function in between – destroying their local objects on the way – until a matching catch block handles it. Exceptions cannot be ignored like return codes, they work in constructors and operators, and together with RAII they guarantee that files, locks and memory are released on every path. This page covers try/throw/catch, the standard exception classes, custom exceptions, stack unwinding, noexcept, exceptions in constructors and destructors, the exception-safety guarantees interviewers ask about, and when to prefer std::optional or std::expected. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – all verified on a real C++ compiler.

On this page

  • try, throw and catch
  • The standard exception hierarchy, catch order and catch(...)
  • Custom exception classes
  • Stack unwinding and RAII
  • Rethrowing, translating and nesting exceptions
  • noexcept, destructors, constructors and exception-safety guarantees

try, throw and catch

throw expression; creates an exception object and starts looking for a handler. Code inside a try block is protected; the catch blocks after it are tried in order, and the first whose type matches handles the exception. Execution then continues after the last catch block – never back at the throw.

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

double divide(double a, double b) {
    if (b == 0) throw std::invalid_argument("division by zero");   // throw: stop here and report
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 4) << '\n';
        std::cout << divide(1, 0) << '\n';      // throws: the rest of the try block is skipped
        std::cout << "not printed\n";
    } catch (const std::invalid_argument& e) {  // catch by const reference
        std::cout << "error: " << e.what() << '\n';
    }
    std::cout << "program continues\n";
    return 0;
}

Output

2.5
error: division by zero
program continues

The standard exception hierarchy

Class (header)MeaningThrown by, for example
std::exception (<exception>)base of all standard exceptions; virtual what()–
std::logic_error (<stdexcept>)a bug: a precondition was violated–
  invalid_argument, domain_error, length_error, out_of_rangespecific logic errorsstd::stoi, vector::at, string::substr
std::runtime_error (<stdexcept>)a problem only detectable at run time–
  range_error, overflow_error, underflow_error, system_errorspecific run-time errorsstd::thread, filesystem
std::bad_alloc (<new>)memory allocation failednew, containers
std::bad_cast, bad_optional_access, bad_variant_access, bad_any_castwrong type accessdynamic_cast to reference, optional::value

Always catch by const reference: it avoids copying and slicing, so what() of a derived class still works. Order catch blocks from most specific to most general, and put catch (...) last.

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

void risky(int kind) {
    switch (kind) {
        case 1: throw std::out_of_range("index 9 of 3");
        case 2: throw std::runtime_error("disk full");
        case 3: throw std::string("a string, not an exception class");
        case 4: throw 42;
    }
}

int main() {
    for (int k = 1; k <= 4; ++k) {
        try {
            risky(k);
        } catch (const std::out_of_range& e) {      // most specific first
            std::cout << "out_of_range: " << e.what() << '\n';
        } catch (const std::exception& e) {         // any standard exception
            std::cout << "exception: " << e.what() << '\n';
        } catch (const std::string& s) {
            std::cout << "string: " << s << '\n';
        } catch (...) {                             // anything else
            std::cout << "unknown exception\n";
        }
    }
    return 0;
}

Output

out_of_range: index 9 of 3
exception: disk full
string: a string, not an exception class
unknown exception

Custom exception classes

Derive your exceptions from std::runtime_error or std::logic_error (or std::exception). Callers can then catch them specifically, or generically as std::exception, and they can carry extra data about the failure.

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

// Derive from a standard exception: callers can catch it specifically or as std::exception
class InsufficientFunds : public std::runtime_error {
    double needed_;
public:
    InsufficientFunds(double balance, double amount)
        : std::runtime_error("insufficient funds: balance " + std::to_string(static_cast<int>(balance)) +
                             ", requested " + std::to_string(static_cast<int>(amount))),
          needed_(amount - balance) {}
    double needed() const noexcept { return needed_; }
};

class Account {
    double balance_ = 0;
public:
    void deposit(double x) {
        if (x <= 0) throw std::invalid_argument("deposit must be positive");
        balance_ += x;
    }
    void withdraw(double x) {
        if (x > balance_) throw InsufficientFunds(balance_, x);
        balance_ -= x;
    }
    double balance() const { return balance_; }
};

int main() {
    Account a;
    a.deposit(500);
    try {
        a.withdraw(200);
        a.withdraw(450);
    } catch (const InsufficientFunds& e) {
        std::cout << e.what() << " (short by " << e.needed() << ")\n";
    }
    try { a.deposit(-5); } catch (const std::exception& e) { std::cout << e.what() << '\n'; }
    std::cout << "balance " << a.balance() << '\n';
    return 0;
}

Output

insufficient funds: balance 300, requested 450 (short by 150)
deposit must be positive
balance 300

Stack unwinding and RAII

When an exception leaves a function, every fully constructed local object in that function is destroyed, in reverse order – this is stack unwinding. That is why RAII (resources owned by objects with destructors) makes C++ code exception-safe automatically: smart pointers, lock guards and file streams release their resources whatever happens.

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

struct Guard {
    std::string name;
    explicit Guard(std::string n) : name(std::move(n)) { std::cout << "acquire " << name << '\n'; }
    ~Guard() { std::cout << "release " << name << '\n'; }
};

void level3() { Guard g("file"); throw std::runtime_error("parse failed"); }
void level2() { Guard g("lock"); level3(); std::cout << "never\n"; }
void level1() { Guard g("connection"); level2(); }

int main() {
    try {
        level1();
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << '\n';     // every Guard was released on the way here
    }
    return 0;
}

Output

acquire connection
acquire lock
acquire file
release file
release lock
release connection
caught: parse failed

Rethrowing, translating and nesting

Inside a catch block, throw; rethrows the current exception unchanged (with its real dynamic type). throw e; would throw a copy of the caught type – sliced if caught as a base class. To turn a low-level error into a higher-level one without losing the cause, use std::throw_with_nested and later std::rethrow_if_nested.

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

struct DbError : std::runtime_error { using std::runtime_error::runtime_error; };

void query() { throw DbError("connection reset"); }

void load_user() {
    try {
        query();
    } catch (const std::exception& e) {
        std::cout << "log: " << e.what() << '\n';
        throw;                                  // rethrow the ORIGINAL exception (keeps its real type)
    }
}

void load_profile() {
    try {
        load_user();
    } catch (const DbError& e) {
        // translate a low-level error into a higher-level one, keeping the cause
        std::throw_with_nested(std::runtime_error("could not load profile"));
    }
}

void print_chain(const std::exception& e, int depth = 0) {
    std::cout << std::string(depth * 2, ' ') << e.what() << '\n';
    try { std::rethrow_if_nested(e); }
    catch (const std::exception& inner) { print_chain(inner, depth + 1); }
}

int main() {
    try { load_profile(); }
    catch (const std::exception& e) { print_chain(e); }
    return 0;
}

Output

log: connection reset
could not load profile
  connection reset

noexcept and destructors

noexcept promises that a function will not throw; if it does, std::terminate ends the program. The noexcept(expr) operator asks at compile time whether an expression can throw. Destructors are noexcept by default and must not let exceptions escape – throwing during stack unwinding would terminate the program. Move constructors should be noexcept so containers can use them.

#include <iostream>
#include <stdexcept>
#include <type_traits>
#include <vector>

int safe_add(int a, int b) noexcept { return a + b; }   // promises never to throw
int may_throw(int a) { if (a < 0) throw std::domain_error("negative"); return a; }

struct Widget {
    ~Widget() { std::cout << "~Widget (destructors are noexcept by default)\n"; }
};

int main() {
    std::cout << noexcept(safe_add(1, 2)) << noexcept(may_throw(1)) << ' '
              << std::is_nothrow_destructible_v<Widget> << ' '
              << std::is_nothrow_move_constructible_v<std::vector<int>> << '\n';
    try {
        Widget w;
        may_throw(-1);
    } catch (const std::domain_error& e) {
        std::cout << "caught " << e.what() << '\n';
    }
    // If a noexcept function DID throw, std::terminate would end the program immediately.
    return 0;
}

Output

10 1 1
~Widget (destructors are noexcept by default)
caught negative

Exceptions in constructors

A constructor that cannot create a valid object should throw – there is no return value to check. If it throws, the object never existed: its destructor does not run, but every member and base that was already constructed is destroyed. So keep resources in members that manage themselves (like unique_ptr), never in raw pointers allocated in the constructor body.

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

struct Part {
    std::string name;
    explicit Part(std::string n) : name(std::move(n)) { std::cout << "+" << name << ' '; }
    ~Part() { std::cout << "-" << name << ' '; }
};

class Machine {
    Part engine_;
    std::unique_ptr<Part> wheels_;
    Part radio_;
public:
    explicit Machine(bool faulty)
        : engine_("engine"), wheels_(std::make_unique<Part>("wheels")), radio_("radio") {
        if (faulty) throw std::runtime_error("self-test failed");
        std::cout << "[Machine ready] ";
    }
    ~Machine() { std::cout << "[~Machine] "; }
};

int main() {
    try {
        Machine m(true);
    } catch (const std::exception& e) {
        std::cout << "| " << e.what() << '\n';     // ~Machine never ran, but every member was destroyed
    }
    return 0;
}

Output

+engine +wheels +radio -radio -wheels -engine | self-test failed

Exception-safety guarantees

GuaranteePromise if an exception is thrownExample
No-thrownever throwsdestructors, swap, move operations
Strongthe state is unchanged ("commit or roll back")vector::push_back, copy-and-swap
Basicno leaks, invariants hold, but the state may have changedmost operations
Noneanything may happenavoid

Exceptions or error values?

Use exceptions for errors that are rare and that the immediate caller usually cannot fix: a missing config file, a broken connection, a failed allocation. For expected, everyday outcomes – "user not found", "invalid input from a form" – return std::optional or std::expected (see Modern C++ Features). Never use exceptions for normal control flow such as ending a loop.

Common mistakes

  • Catching by value – copies and slices derived exceptions.
  • Catching the base class first – the specific handlers after it are unreachable.
  • throw e; instead of throw; when rethrowing – loses the dynamic type.
  • Throwing from a destructor – std::terminate.
  • Raw new in a constructor before something that can throw – leak.
  • Throwing pointers (throw new MyError) – who deletes it? Throw by value.
  • Swallowing exceptions with an empty catch (...) – hides real bugs.

Key points to remember

  • throw by value, catch by const reference.
  • Order catch blocks from specific to general; catch (...) last.
  • Derive custom exceptions from std::runtime_error / std::logic_error.
  • Stack unwinding destroys locals – RAII makes cleanup automatic.
  • throw; rethrows the original exception.
  • Destructors and moves should be noexcept; a throwing noexcept function terminates.
  • Constructors signal failure by throwing; the destructor then does not run.

Frequently asked questions

What happens if an exception is never caught?

std::terminate is called, which by default aborts the program (whether the stack is unwound first is implementation-defined).

Are exceptions slow?

With modern "zero-cost" implementations, code that does not throw runs at full speed; throwing and catching is relatively expensive, which is why exceptions are for exceptional situations.

Can I throw any type?

Yes – ints, strings, anything copyable or movable – but throwing classes derived from std::exception is the convention, so callers can catch everything with one handler and call what().

Where can I learn more?

Read C++ Exception Handling, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links