C/C++ Arena

Step 1 of 6

Bugs vs expected failures

Two very different things can go wrong:

  1. Bugs (a broken assumption in your code, like a negative array size). Use assert(condition) from <cassert>. If the condition is false, the program stops immediately and tells you where. It's a tripwire for programmers.
  2. Expected failures (bad user input, a missing file, a player not found). These aren't bugs, so the code must handle them and keep going.

Exceptions (throw/try/catch) are standard C++'s general tool for failure: a throw unwinds the stack to the nearest matching catch, running destructors on the way (RAII again!).

try {
    int x = std::stoi("abc");   // throws std::invalid_argument
} catch (const std::exception& e) {
    std::cout << e.what();
}

This site's compiler targets WebAssembly without exception support, so throw won't compile here. That's a real-world situation too: games, embedded systems and many large codebases (Google's, for example) build with exceptions turned off. The rest of this module covers the exception-free patterns they use.

Your turn: add an assert that n is positive. With a valid call the program prints ok.

Next: Status codes