Loading...

C++ Exceptions

The auto page left one line on the screen in box.cpp: pine, after a set walk with const auto& w. This page opens the Errors and Files module on purpose. The workshop file on disk stays box.cpp so you keep one familiar build path. The new work stores two ints in a vector, prints a safe at(0) read, and names what happens when at asks for a missing index. The checked screen shows one line: 2.
An exception is C++ saying a rule broke while the program was running. On this page you write std::vector<int> slots = {2, 4}; and then std::cout << slots.at(0) << std::endl;. Reading at(0) is reading the first value with a bounds-checked call. Reading a missing index like at(5) is reading a path that throws std::out_of_range and stops the normal run. The checked file only prints the safe at(0) so the screen is quiet with 2.
Programs use exceptions to report broken run-time rules instead of printing a wrong value and continuing. You do not keep the set and auto loop as the lesson body on this page. Catching with try and catch waits for the next page on purpose. Here the point is only a safe at print and knowing a bad at throws and stops. The build command stays familiar: one source file box.cpp, one output name box, one run that prints 2. Keep #include <iostream> and #include <vector> together at the top. You compile only box.cpp again for this workshop file on disk.
Think of at as a careful shelf read that refuses a missing slot. Shelf zero holds 2, so the safe print shows 2. Shelf five was never written, so a real at(5) would throw and stop. This page keeps the safe file as the checked body. The stop story lives in the prose and the table so you recognize the exception name before you learn to catch it.

Inside main, write std::vector<int> slots = {2, 4};, then std::cout << slots.at(0) << std::endl;, then return 0;. Keep the two includes at the top of the file. Do not call at(5) in the checked body. Do not keep the old set loop as the lesson path on this page.
Walk the run carefully from the first line of main. The program starts at main. slots holds 2 and 4. at(0) returns 2. Printing that value shows 2 on the screen. Then main returns and the program ends. There is one line on the screen. It is 2, not pine. The checked file always uses the safe index so the screen is quiet.
Say the steps out loud once while you read the file. Make slots. Read at zero. Print 2. Return. That short story is the whole checked workshop path. Nothing else belongs in the checked body. No bad index. No try block. No extra include beyond iostream and vector. When the screen shows 2, the safe story matched the source.

If you change only the print to slots.at(5), the program throws std::out_of_range and stops. That failed experiment stays in the prose. The checked file always keeps at(0) so the screen is 2.
If you forget #include <vector>, the build fails about std::vector. The checked file keeps that include next to iostream.
A common mistake is to invent a try block on this page before the next lesson. Another common mistake is to treat a stack report as a normal cout line. A third mistake is to keep the old set and auto body and never add the vector. A fourth mistake is to print a literal 2 and never use at. A fifth mistake is to use slots[5] as the teaching crash when this page names at and out_of_range.
This page stops before the next tool, where try and catch catch an exception and continue. The next page names that tool once at the end. The safe at(0) you have just written only shows a quiet finish. Keep the safe index in the checked file so the order stays clear for a first careful reading.
Remember that naming out_of_range does not catch it. You still leave catching for the next page. After the safe print the screen is 2. After you undo a bad-index experiment the checked file returns to at(0). Stability of the checked file matters as much as learning the stop story itself.

Open box.cpp. Remove the set and auto loop from the auto demo. Add #include <vector> and drop #include <set> and #include <string> if they are unused. In main, create slots with 2 and 4, print slots.at(0), and return. The file name on disk stays box.cpp. The checked file is below, and the new lines are the vector and the safe at print.

box.cpp prints slots.at(0) as 2

cpp
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> slots = {2, 4};
    std::cout << slots.at(0) << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 box.cpp -o box, then run ./box. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 box.cpp -o box. The screen shows one line: 2.
Check that line first on the screen. The safe at(0) read returned 2, so the print showed 2. The table gives each row its piece, so compare your run with it line by line before you move on to experiments. If the screen shows pine, the old set loop is still there. If the build fails about vector, check #include <vector>. If you temporarily try at(5), expect a stop that names std::out_of_range, then restore at(0).

📊 exceptions and what the screen shows

Piece What the screen shows
First 2, because at(0) reads the first value in slots
Last 2, because the safe program prints one line and stops
Rule at checks bounds; a missing index throws std::out_of_range and stops
Screen 2

Try one change at a time. Temporarily change the print to slots.at(1) and rebuild so the screen shows 4, then restore at(0) for 2. Next, temporarily try slots.at(5) only long enough to see the run stop with out_of_range, then restore the safe print immediately. Do not leave the crashing index in the checked file. Each experiment changes one thing on purpose, so you see either another valid slot or the stop story. Undo each change before the next one starts, so the file always returns to the checked workshop version with slots.at(0) once again after every single careful try back on disk again.
This page ends the first exceptions tool and stops before the next one. The next page is try-catch, which catches an exception so the program can continue. The safe at call you have just written only shows a quiet finish in box.cpp. You leave with one line on the screen: 2. Count the lines before you leave. There is exactly one printed line on that final screen, and that single printed line on the screen is still just 2 alone right there now after the final successful build run on disk today now after the safe at read.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top