These are the notes for C++ episode 31. Programs meet bad input, missing files and failed payments. This episode shows why the obvious way to report a problem, an error code, fails silently, what the library does instead (it throws), and how try, catch and throw let a function deep inside your program report a problem to the code that can handle it. Every example below was compiled with g++ -O2 -std=c++17 main.cpp -o main (g++ 13.3, the same command as the SyntaxPilot compiler) and run; outputs and error messages are copied from those runs.
The problem: an error code nobody checks
A train booking form asks for your age. toAge must return an int, so for bad input it returns -1, an error code ("no real person is -1 years old"). The caller forgets to check:
#include <iostream>
#include <string>
using namespace std;
int toAge(string s) {
for (char c : s)
if (c < '0' || c > '9')
return -1; // error code: "bad input"
return stoi(s);
}
int main() {
string text;
cin >> text;
int age = toAge(text); // forgot to check for -1
cout << "Next year you'll be " << age + 1 << endl;
return 0;
}
Input: abc
Output:
Next year you'll be 0
No error, no crash, just a wrong answer. With error codes, forgetting to check is the default, and the program carries on with a fake value.
What the library does: it throws
stoi ("string to int", from <string>) doesn't return a fake number for "abc":
#include <iostream>
#include <string>
using namespace std;
int main() {
string text;
cin >> text;
int age = stoi(text); // string to int
cout << "Next year you'll be " << age + 1 << endl;
return 0;
}
Input: abc
Output:
terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
(the program is aborted)
stoi threw an exception: a signal that says "I can't do this". Nobody caught it, so C++ called std::terminate and the program was aborted. what(): stoi is the exception's message.
Step 1: a fire alarm in a hostel
| In a hostel | In C++ |
|---|---|
| A student sees a fire and pulls the alarm (they can't put it out themselves) | throw: a function hits a problem it can't fix |
| The alarm rings straight down, skipping every floor; no handwritten note to forget | the exception travels up through the calling functions, skipping the rest of each |
| The warden, who knows what to do, handles it | catch: the place that can deal with the problem |
Step 2: try and catch
Put the risky code in a try block, and the handling code in a catch block for the exception type you expect. e.what() gives the message. The standard exception types live in <stdexcept>.
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
string text;
cin >> text;
try {
int age = stoi(text);
cout << "Next year you'll be " << age + 1 << endl;
} catch (const invalid_argument& e) {
cout << "Not a number: " << e.what() << endl;
}
cout << "Booking form still open" << endl;
return 0;
}
Input: abc
Output:
Not a number: stoi
Booking form still open
When stoi threw, the rest of the try block was skipped, so the wrong answer was never printed, and the program carried on after the catch. With valid input (30) there is no exception and the catch block is skipped entirely:
Next year you'll be 31
Booking form still open
With a huge number (99999999999), stoi throws a different type, out_of_range (the number doesn't fit in an int), and our catch only handles invalid_argument:
terminate called after throwing an instance of 'std::out_of_range'
what(): stoi
An exception whose type no catch matches still terminates the program. Step 4 adds a second catch block for it.
Step 3: throw your own, from deep inside
withdraw is three calls deep (main → payBill → withdraw). It can't fix a low balance, and it knows nothing about the user's screen, so it throws a runtime_error. A Receipt object prints when it is created and destroyed:
#include <iostream>
#include <stdexcept>
using namespace std;
struct Receipt {
Receipt() { cout << " receipt started" << endl; }
~Receipt() { cout << " receipt torn up" << endl; }
};
int balance = 1200;
void withdraw(int amount) {
if (amount > balance) throw runtime_error("not enough balance");
balance -= amount;
}
void payBill(int amount) {
Receipt r;
withdraw(amount);
cout << " paid " << amount << ", left " << balance << endl;
}
int main() {
try {
payBill(500);
payBill(5000);
cout << "all paid" << endl; // never reached
} catch (const runtime_error& e) {
cout << "Payment failed: " << e.what() << endl;
}
return 0;
}
Output:
receipt started
paid 500, left 700
receipt torn up
receipt started
receipt torn up
Payment failed: not enough balance
After the throw, paid ... and all paid were never printed: the exception jumped straight from withdraw, through payBill, into main's catch. But the receipt was still torn up: on the way out, C++ destroys every local object in every function it leaves. This is stack unwinding, and it's why RAII and smart pointers (episode 28) never leak, even when an exception flies past.
Rethrowing with throw;
A middle function may want to react (write a log line) without fixing the problem. A bare throw; inside a catch passes the same exception on:
#include <iostream>
#include <stdexcept>
using namespace std;
int balance = 1200;
void withdraw(int amount) {
if (amount > balance) throw runtime_error("not enough balance");
balance -= amount;
}
void payBill(int amount) {
try {
withdraw(amount);
} catch (const runtime_error& e) {
cout << "Log: payBill(" << amount << ") failed" << endl;
throw; // pass it on
}
}
int main() {
try {
payBill(5000);
} catch (const runtime_error& e) {
cout << "Screen: payment failed, " << e.what() << endl;
}
return 0;
}
Output:
Log: payBill(5000) failed
Screen: payment failed, not enough balance
Step 4: several catch blocks
Different things can go wrong, so a try can have several catch blocks. vector::at checks the index and throws out_of_range (square brackets [] don't check):
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
vector<int> prices = {10, 25, 15}; // chai, coffee, samosa
string item;
while (cin >> item) {
try {
int i = stoi(item);
int price = prices.at(i);
cout << "price: " << price << endl;
} catch (const invalid_argument& e) {
cout << item << ": not a number" << endl;
} catch (const out_of_range& e) {
cout << item << ": no such item" << endl;
}
}
return 0;
}
Input: 1 chai 7
Output:
price: 25
chai: not a number
7: no such item
The exception family tree
| Type | Header | Meaning | Thrown by, for example |
|---|---|---|---|
exception |
<exception> |
the parent of all standard exceptions; has what() |
(catch it as a last net) |
logic_error |
<stdexcept> |
a mistake in how the code was used | |
invalid_argument |
<stdexcept> |
an argument that makes no sense (a kind of logic_error) |
stoi("abc") |
out_of_range |
<stdexcept> |
an index or value outside the allowed range (a kind of logic_error) |
v.at(7), stoi("99999999999") |
runtime_error |
<stdexcept> |
something went wrong in the world while running | your own: a low balance |
bad_alloc |
<new> |
new couldn't get memory |
new int[huge] |
Because they all inherit from exception (inheritance, episode 15), catch (const exception& e) catches all of them.
The order trap
C++ tries the catch blocks from top to bottom and takes the first one that matches. A general handler first swallows everything:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> prices = {10, 25, 15};
try {
cout << prices.at(5) << endl;
} catch (const exception& e) { // the general one first
cout << "something went wrong" << endl;
} catch (const out_of_range& e) {
cout << "no such item" << endl;
}
return 0;
}
Compiler warning:
main.cpp:12:7: warning: exception of type 'std::out_of_range' will be caught by earlier handler [-Wexceptions]
Output:
something went wrong
Always put the specific catches first and the general ones last.
Step 5: your own exception class
Inherit from runtime_error and add the data the handler needs:
#include <iostream>
#include <stdexcept>
using namespace std;
struct LowBalance : runtime_error {
int shortBy;
LowBalance(int s)
: runtime_error("not enough balance"), shortBy(s) {}
};
int balance = 1200;
void withdraw(int amount) {
if (amount > balance)
throw LowBalance(amount - balance);
balance -= amount;
}
int main() {
try {
withdraw(5000);
} catch (const LowBalance& e) {
cout << e.what() << ": add " << e.shortBy << " rupees" << endl;
}
return 0;
}
Output:
not enough balance: add 3800 rupees
Because LowBalance is a runtime_error, a catch (const runtime_error& e) or catch (const exception& e) would also catch it.
noexcept that throws, and catch (...)
catch (...) catches anything. But a function marked noexcept (episode 29) that throws anyway ends the program at once, and no catch can help:
#include <iostream>
#include <stdexcept>
using namespace std;
void refund() noexcept { // "I never throw"
throw runtime_error("bank server down");
}
int main() {
try {
refund();
} catch (...) { // catch anything
cout << "caught it" << endl;
}
return 0;
}
Compiler warning:
main.cpp:6:5: warning: 'throw' will always call 'terminate' [-Wterminate]
Output:
terminate called after throwing an instance of 'std::runtime_error'
what(): bank server down
(the program is aborted)
Using exceptions well
| Rule | Why |
|---|---|
| Throw for real problems the function can't fix | bad input, a low balance, a missing file |
| Catch where you can actually do something | often near main or the user screen, not in every function |
Catch by const reference: catch (const exception& e) |
catching by value copies the object, and a copy into a parent type loses the child's extra data (shortBy): slicing |
Specific catches first, catch (...) only as a last net |
the first matching catch wins |
| Let destructors clean up (RAII) | they run during stack unwinding |
| Don't use exceptions for normal control flow | throwing is slow compared with an if; "end of the loop" is not exceptional |
Rethrow with plain throw; |
inside a catch, throw; passes the same exception on |
Common mistakes (and the real g++ messages)
| Mistake | What happens | Fix |
|---|---|---|
| An exception nobody catches | terminate called after throwing an instance of 'std::invalid_argument' / what(): stoi, program aborted |
try { ... } catch (const invalid_argument& e) { ... } |
General catch before a specific one |
warning: exception of type 'std::out_of_range' will be caught by earlier handler [-Wexceptions] |
specific catches first |
Throwing from a noexcept function |
warning: 'throw' will always call 'terminate' [-Wterminate], then terminate |
remove noexcept, or don't throw |
| An error code the caller forgets to check | compiles; Next year you'll be 0 |
throw an exception |
Catching by value: catch (exception e) |
compiles; the object is copied and sliced | catch (const exception& e) |
Forgetting #include <stdexcept> for runtime_error |
may compile by accident through other headers; not guaranteed | include <stdexcept> |
Mini project: a booking form that keeps asking
Keep asking for an age until it is a valid number between 1 and 120. stoi reports non-numbers; our own check throws out_of_range for impossible ages:
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int readAge(const string& text) {
int age = stoi(text); // may throw invalid_argument
if (age < 1 || age > 120)
throw out_of_range("age must be 1 to 120");
return age;
}
int main() {
string text;
while (cout << "Age: ", cin >> text) {
try {
int age = readAge(text);
cout << "Booked. Senior discount: " << (age >= 60 ? "yes" : "no") << endl;
break;
} catch (const invalid_argument& e) {
cout << text << " is not a number, try again" << endl;
} catch (const out_of_range& e) {
cout << e.what() << ", try again" << endl;
}
}
return 0;
}
Input:
abc
250
-3
34
Output:
Age: abc is not a number, try again
Age: age must be 1 to 120, try again
Age: age must be 1 to 120, try again
Age: Booked. Senior discount: no
Practice
- Ask for an age until the user types a valid number (the mini project above).
- Write a
Walletclass whosepay(int)throwsLowBalancewith the missing amount. - A chai menu: catch
out_of_rangefromvector::atfor item numbers past the end. - Add a
Receiptto three nested functions and watch stack unwinding.
Solutions
Exercise 2:
#include <iostream>
#include <stdexcept>
using namespace std;
struct LowBalance : runtime_error {
int shortBy;
LowBalance(int s) : runtime_error("not enough balance"), shortBy(s) {}
};
class Wallet {
int balance;
public:
Wallet(int b) : balance(b) {}
void pay(int amount) {
if (amount > balance) throw LowBalance(amount - balance);
balance -= amount;
cout << "paid " << amount << ", left " << balance << endl;
}
};
int main() {
Wallet w(1000);
try {
w.pay(300);
w.pay(900);
w.pay(50);
} catch (const LowBalance& e) {
cout << e.what() << ": short by " << e.shortBy << endl;
}
return 0;
}
Output:
paid 300, left 700
not enough balance: short by 200
Exercise 4:
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
struct Receipt {
string where;
Receipt(string w) : where(w) { cout << "open " << where << endl; }
~Receipt() { cout << "close " << where << endl; }
};
void bank() { Receipt r("bank"); throw runtime_error("server down"); }
void gateway() { Receipt r("gateway"); bank(); }
void checkout() { Receipt r("checkout"); gateway(); }
int main() {
try {
checkout();
} catch (const exception& e) {
cout << "caught: " << e.what() << endl;
}
return 0;
}
Output:
open checkout
open gateway
open bank
close bank
close gateway
close checkout
caught: server down
The receipts close in reverse order (bank, gateway, checkout) before the catch runs: that is stack unwinding.
Quick quiz
What does this print?
try {
cout << "A";
throw runtime_error("x");
cout << "B";
} catch (const exception& e) {
cout << "C";
}
cout << "D";
Answer
ACD. A prints, the throw skips B and jumps to the catch (a runtime_error is an exception), which prints C. After the catch the program carries on: D.
Interview questions
- What is stack unwinding? When an exception is thrown, C++ leaves each function on the way to the matching
catch, destroying every local object (running its destructor) as it goes. - Why catch by reference? No copy, no slicing of derived exception types, and polymorphic
what()still works. - What happens if an exception is never caught?
std::terminateis called, which aborts the program. - What happens if a
noexceptfunction throws?std::terminate, immediately; the exception can't leave the function. - Should destructors throw? No. Destructors are
noexceptby default; throwing during stack unwinding terminates the program. - Error codes vs exceptions? Error codes are cheap but easy to ignore and clutter every caller; exceptions can't be ignored silently and separate error handling from normal code, at a cost when thrown.
- What is
catch (...)? A handler that catches any exception, of any type; usually the last handler, often to log and rethrow withthrow;. - What are exception safety guarantees? No-throw (never fails), strong (if it fails, nothing changed), basic (if it fails, nothing leaks and objects are valid).
Glossary
| Term | Meaning, with an example |
|---|---|
| error code | A special return value that means "it failed", like -1 from toAge. Easy to ignore. |
| exception | An object thrown to report a problem: throw runtime_error("not enough balance"); |
throw |
Raises an exception and leaves the current function immediately. |
try block |
The code that might throw: try { int age = stoi(text); } |
catch block |
Handles one type of exception: catch (const invalid_argument& e) { ... } |
| handler | Another name for a catch block. |
what() |
The member function that returns an exception's message. |
stoi |
"String to int": stoi("30") is 30; stoi("abc") throws invalid_argument. |
std::terminate |
Ends the program when an exception isn't caught (or escapes a noexcept function). |
abort |
How terminate ends the program: immediately, without normal cleanup. |
| stack unwinding | Leaving functions on the way to a catch, destroying their local objects. |
| RAII | Cleanup in destructors, so it happens during unwinding too (episode 28). |
exception |
The base class of all standard exceptions (<exception>). |
runtime_error |
A standard exception for problems found while running (<stdexcept>). |
logic_error |
A standard exception for mistakes in how code was used. |
invalid_argument |
A logic_error for an argument that makes no sense. |
out_of_range |
A logic_error for a value or index outside the allowed range, e.g. v.at(7). |
| custom exception | Your own class deriving from a standard one, e.g. LowBalance : runtime_error with shortBy. |
catch (...) |
A handler that catches any exception. |
| slicing | Copying a derived object into a base-class object, losing the derived part. |
noexcept |
A promise that a function never throws; breaking it calls terminate. |
| rethrow | throw; inside a catch passes the same exception on to an outer handler. |
Summary
- Error codes are easy to ignore: a silent wrong answer.
- An uncaught exception calls
terminate: loud, but never silently wrong. trythe risky part,catch (const T& e)the problem,e.what()for the message.throwjumps straight to the nearest matchingcatch; destructors run on the way (stack unwinding).- Several catches: specific first, general last. Your own exceptions inherit
runtime_error. - A throwing
noexceptfunction terminates the program.
Next episode: close your booking app and every booking is gone. How do you save data to a file and read it back tomorrow? File streams.