11.4 — Exceptions: handling errors
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 zeroWhen something is thrown, C++ jumps straight to the matching catch, skipping everything in between.
Exceptions you'll meet#
std::stoi("abc")throwsstd::invalid_argument.v.at(99)on a small vector throwsstd::out_of_range.
Good habit
Catch exceptions by const&. Use exceptions for real problems, not for normal choices that an if can handle.
Tip: press ← / → to move between lessons, / to search.