Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    C++C++

    C++ fundamentals

    • Your first C++ program
    • Variables and types
    • Operators and input
    • Conditions: if and switch
    • Loops

    Functions and collections

    • Functions
    • References: by value or by reference?
    • Strings and arrays
    • std::vector
    • map, set and unordered_map

    Memory and pointers

    • Pointers
    • Stack, heap, new and delete
    • Smart pointers and RAII

    Classes and OOP

    • struct and class
    • Constructors and destructors
    • Inheritance and virtual functions
    • Templates

    The STL and professional C++

    • Algorithms and lambdas
    • Exceptions
    • Recursion
    • Project: a grade book
    C++

    The STL and professional C++ · Lesson 19 of 21

    Exceptions

    throw, try and catch, the standard error types, and how RAII fits in.

    9 minutes2 games

    When a function hits something it can't continue with (bad input, a missing file), it can throw an exception. Execution stops at once and unwinds outward to the nearest matching catch. With no catch at all, the program terminates.

    C++
    #include <iostream>
    #include <stdexcept>
    #include <string>
    #include <vector>
    
    double average(const std::vector<int>& v) {
        if (v.empty()) throw std::invalid_argument("average of an empty list");
        int sum = 0;
        for (int x : v) sum += x;
        return static_cast<double>(sum) / v.size();
    }
    
    int main() {
        try {
            std::cout << average({80, 90}) << "\n";
            std::cout << average({}) << "\n";          // throws
            std::cout << "never printed\n";
        } catch (const std::invalid_argument& e) {
            std::cout << "bad input: " << e.what() << "\n";
        }
    
        std::vector<int> v = {1, 2, 3};
        try {
            std::cout << v.at(10) << "\n";
        } catch (const std::out_of_range& e) {
            std::cout << "out of range\n";
        }
        std::cout << "still running\n";
        return 0;
    }
    • std::exception
      • std::logic_error
        • std::invalid_argument
        • std::out_of_range
      • std::runtime_error
        • std::overflow_error
      • std::bad_alloc (new failed)

    The standard types form a tree: catch (const std::exception& e) catches any of them.

    Important

    Always catch by const reference (const std::exception&). As an exception leaves a function, every local object's destructor runs (stack unwinding), so RAII resources free themselves. One more reason not to use raw new/delete.

    What's the output?

    #include <iostream>
    #include <stdexcept>
    struct Guard {
        ~Guard() { std::cout << "G"; }
    };
    void risky() {
        Guard g;
        std::cout << "1";
        throw std::runtime_error("x");
        std::cout << "2";
    }
    int main() {
        try { risky(); } catch (const std::exception&) { std::cout << "C"; }
        std::cout << "\n";
    }

    What will this code print?

    Interview question

    When do you use exceptions versus error codes? What does noexcept mean?

    Exercise

    Write int toPercent(int part, int whole) that throws std::invalid_argument when whole is zero and otherwise returns part * 100 / whole. In main: print toPercent(3, 4), then try toPercent(1, 0), catch the exception and print error.

    Expected output:
    75
    error
    C++
    #include <iostream>
    #include <stdexcept>
    
    int toPercent(int part, int whole) {
        return part * 100 / whole;
    }
    
    int main() {
        std::cout << toPercent(3, 4) << "\n";
        
        return 0;
    }

    Learn more from

    • learncpp: Basic exception handlinglearncpp.com
    • cppreference: Exceptionsen.cppreference.com
    • isocpp FAQ: Exceptions and error handlingisocpp.org

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousAlgorithms and lambdasNextRecursion
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.