11.4 — Exceptions: handling errors

📘 Chapter 11⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

When things go wrong#

Sometimes a function can't do its job: a file is missing, or the input is bad. It can throw an exception to say "something went wrong".

C++
#include <stdexcept> double divide(double a, double b){    if (b == 0)        throw std::invalid_argument { "can't divide by zero" };    return a / b;}

try and catch#

Code that might throw goes in a try block. The catch block handles the problem:

C++
try{    std::cout << divide(10, 0) << '\n';    std::cout << "This line is skipped.\n";}catch (const std::exception& e){    std::cout << "Error: " << e.what() << '\n';}
Output
Error: can't divide by zero

When something is thrown, C++ jumps straight to the matching catch, skipping everything in between.

Exceptions you'll meet#

  • std::stoi("abc") throws std::invalid_argument.
  • v.at(99) on a small vector throws std::out_of_range.
Good habit

Catch exceptions by const&. Use exceptions for real problems, not for normal choices that an if can handle.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.