Lesson 188 +10 XP

Try, Catch, Throw

Try, Catch, Throw

In C++, an exception is a response to an exceptional circumstance that arises while a program is running. The three keywords try, catch, and throw work together so you can throw an error and catch it later.

The three keywords

  • throw - when a problem occurs, you use throw to signal it.
  • catch - a catch block is where the exception is handled.
  • try - try wraps the statements that might throw.
try {
    int age = 15;
    if (age >= 18) {
        cout << "Access granted.";
    } else {
        throw 505;   // throw an int with the error number
    }
}
catch (int myNum) {
    cout << "Access denied - error number " << myNum;
}

The throw passes the value 505, and the matching catch assigns it to myNum. The block's flow is clear: try watches, throw and catch handle the edge case.

Catching different types

A catch can handle any type: int, double, string, or even a custom class. The type inside the catch clause is the filter - only throws of that type activate it.

try {
    throw 20;      // integer this time
} catch (int e) {
    cout << "Sorry. Error: " << e;   // an int exception
}

The matching catch (int e) block runs its statements, then execution continues after the try-catch.

Multiple catch blocks

You can use more than one catch block, one after another, each handling a different type:

try {
    throw 20;
} catch (int e) {
    cout << "Error with int: " << e;
} catch (...) {
    cout << "Caught something else";
}

The first catch with a matching type runs; the ellipsis ... is a catch-all for any other type.

TL;DR

  • try wraps the code that may throw.
  • throw x raises an exception carrying a value.
  • catch (type var) handles exceptions matching its type.
  • You can throw any type you like.
  • Multiple catch blocks handle different types differently.