0Pricing
C++ Academy · Lesson

try, catch, throw

Handle errors with exceptions.

Signalling Errors with throw

The throw statement raises an exception, abandoning the current path and looking for a handler up the call stack.

#include <iostream>
#include <stdexcept>

int main() {
    try {
        throw std::runtime_error("boom");
    } catch (const std::exception& e) {
        std::cout << e.what() << "\n";
    }
}

try and catch

Code that might throw goes in a try block; matching handlers follow in catch blocks.

#include <iostream>
#include <stdexcept>

int divide(int a, int b) {
    if (b == 0) throw std::invalid_argument("divide by zero");
    return a / b;
}

int main() {
    try {
        std::cout << divide(10, 0) << "\n";
    } catch (const std::invalid_argument& e) {
        std::cout << "error: " << e.what() << "\n";
    }
}

All lessons in this course

  1. try, catch, throw
  2. Exception Safety
  3. noexcept Specifier
  4. Custom Exception Types
← Back to C++ Academy