Loading...

C++ try and catch

The exceptions page left one line on the screen in box.cpp: 2, after a safe slots.at(0) print. This page stays in 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 keeps the same slots vector, calls the bad at(5) inside try, catches std::out_of_range, and prints caught. The screen shows one line: caught.
A try block marks code that might throw. A catch block runs when a matching exception appears. On this page you write std::vector<int> slots = {2, 4};, then try { std::cout << slots.at(5) << std::endl; } and catch (const std::out_of_range&) { std::cout << "caught" << std::endl; }. Reading the try body is reading the bad index on purpose. Reading the catch body is reading the recovery print. After the catch runs, main can return normally.
Programs use try and catch when you want to handle a thrown exception instead of letting the whole run stop. You do not keep only the quiet at(0) path as the lesson body on this page. Throwing your own exception with throw waits for the next page on purpose. Here the point is only catching out_of_range from at(5) and printing caught. The build command stays familiar: one source file box.cpp, one output name box, one run that prints caught. Keep #include <iostream>, #include <vector>, and #include <stdexcept> together at the top. You compile only box.cpp again for this workshop file on disk.
Think of try as a net under the bad at call. Without the net, at(5) throws and stops. With the net, the catch prints caught and the program continues to return 0. The previous page taught you the stop name. This page teaches you to catch that name and keep going.

Inside main, write std::vector<int> slots = {2, 4};, then a try that prints slots.at(5), then a catch (const std::out_of_range&) that prints caught, then return 0;. Keep the three includes at the top of the file. Do not leave the bad at outside try in the checked file. Do not catch a different type if you want this workshop path.
Walk the run carefully from the first line of main. The program starts at main. slots holds 2 and 4. The try body calls at(5), which throws std::out_of_range. The matching catch runs and prints caught. Then main returns and the program ends. There is one line on the screen. It is caught, not 2. The checked file always keeps the bad at inside try.
Say the steps out loud once while you read the file. Make slots. Try at five. Catch out_of_range. Print caught. Return. That short story is the whole workshop path. Nothing else belongs in the checked body. No safe-only print as the lesson line. No bare throw of your own value yet. No extra include beyond the three you already keep. When the screen shows caught, the story matched the source.

If you remove the try and call at(5) alone, the program stops with out_of_range again. That experiment can stay in the prose. The checked file always keeps try and catch.
If you forget #include <stdexcept>, the build may fail about std::out_of_range. The checked file keeps that include next to iostream and vector.
A common mistake is to catch the wrong type and still stop. Another common mistake is to print a literal without a catch. A third mistake is to keep only at(0) and never practice the catch path. A fourth mistake is to drop #include <vector> while using std::vector. A fifth mistake is to invent a throw of your own on this page before the next lesson.
This page stops before the next tool, where you write throw yourself. The next page names that tool once at the end. The try and catch you have just written only show catching out_of_range from at. Keep the bad call inside try so the order stays clear for a first careful reading of the file.
Remember that catching does not fix the missing index. It only lets the program continue after the throw. After the catch print the screen is caught. After you undo a safe-only experiment the checked file returns to the try path. Stability of the checked file matters as much as learning the catch itself.

Open box.cpp. Keep the vector includes and slots. Change the safe at(0) print into a try that calls at(5) and a catch that prints caught. Add #include <stdexcept> if it is missing. The file name on disk stays box.cpp. The checked file is below, and the new lines are the try block, the catch block, and the caught print.

box.cpp try at(5) catch out_of_range prints caught

cpp
#include <iostream>
#include <vector>
#include <stdexcept>

int main()
{
    std::vector<int> slots = {2, 4};
    try
    {
        std::cout << slots.at(5) << std::endl;
    }
    catch (const std::out_of_range&)
    {
        std::cout << "caught" << 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: caught.
Check that line first on the screen. The bad at(5) threw, the catch ran, and caught was printed. 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 2, you still print only at(0). If the program stops with no caught line, the catch may be missing. If the build fails about out_of_range, check #include <stdexcept>.

📊 try-catch and what the screen shows

Piece What the screen shows
First caught, because at(5) throws and the catch prints that word
Last caught, because the program prints one line and returns
Rule try marks risky code; catch handles std::out_of_range so the run continues
Screen caught

Try one change at a time. Temporarily change the try body to print slots.at(0) instead, leave the catch as it is, and rebuild. The screen shows 2, because no exception was thrown. Restore at(5) so the checked screen is caught again. Next, temporarily remove the catch and rebuild only long enough to see the stop return, then restore the catch immediately. Each experiment changes one thing on purpose, so the screen shows either a quiet value or the catch path. Undo each change before the next one starts, so the file always returns to the checked workshop version with try around at(5) and catch printing caught once again after every single careful try back on disk again.
This page ends the try-catch tool and stops before the next one. The next page is throw, which lets you throw an exception yourself. The catch you have just written only shows handling out_of_range from at in box.cpp. You leave with one line on the screen: caught. 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 caught alone right there now after the final successful build run on disk today now after the catch print.

🧠 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