Loading...

C++ throw

The try-catch page left one line on the screen in box.cpp: caught, after try around slots.at(5) and a catch of out_of_range. 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 throws your own std::runtime_error inside try, catches it, and prints caught. The screen shows one line: caught.
throw starts an exception on purpose. On this page you write try { throw std::runtime_error("boom"); } and catch (const std::runtime_error&) { std::cout << "caught" << std::endl; }. Reading throw is reading the moment you raise the error. Reading the catch body is reading the recovery print. After the catch runs, main returns normally.
Programs use throw when your own code detects a problem and wants to signal it the same way library calls do. You do not keep the vector at(5) path as the lesson body on this page. Reading a file waits for the next page on purpose. Here the point is only throwing runtime_error and catching it to print caught. The build command stays familiar: one source file box.cpp, one output name box, one run that prints caught. Keep #include <iostream> and #include <stdexcept> together at the top. You compile only box.cpp again for this workshop file on disk.
Think of throw as handing a labeled problem up to the nearest matching catch. The label here is std::runtime_error with the text boom. The catch does not print boom on this page; it prints caught so the screen matches the recovery path you already practiced. The previous page caught a library throw. This page throws your own.

Inside main, write a try that throws std::runtime_error("boom"), then a catch (const std::runtime_error&) that prints caught, then return 0;. Keep the two includes at the top of the file. Do not leave throw 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. The try body throws runtime_error. 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 boom. The checked file always keeps throw inside try.
Say the steps out loud once while you read the file. Try. Throw boom. Catch runtime_error. Print caught. Return. That short story is the whole workshop path. Nothing else belongs in the checked body. No vector. No file open. No extra include beyond iostream and stdexcept. When the screen shows caught, the story matched the source.

If you remove the try and throw alone, the program stops with an uncaught exception. That experiment can stay in the prose. The checked file always keeps try and catch.
If you forget #include <stdexcept>, the build fails about std::runtime_error. The checked file keeps that include next to iostream.
A common mistake is to throw without a matching catch type. Another common mistake is to print boom from the catch when the checked screen is caught. A third mistake is to keep the old vector at body and never write throw. A fourth mistake is to drop #include <iostream> while still printing. A fifth mistake is to open a file on this page before the next lesson.
This page stops before the next tool, where you read text from a file. The next page names that tool once at the end. The throw you have just written only shows raising runtime_error for a matching catch. Keep the throw inside try so the order stays clear for a first careful reading of the file.
Remember that throwing does not print by itself. You still need the catch print for the checked screen. After the catch the screen is caught. After you undo a no-try experiment the checked file returns to the try path. Stability of the checked file matters as much as learning throw itself.

Open box.cpp. Remove the vector and at(5) lines from the try-catch demo. Keep #include <stdexcept>. In main, write try with throw std::runtime_error("boom"); and catch that prints caught. The file name on disk stays box.cpp. The checked file is below, and the new line is the throw call.

box.cpp throw runtime_error then catch prints caught

cpp
#include <iostream>
#include <stdexcept>

int main()
{
    try
    {
        throw std::runtime_error("boom");
    }
    catch (const std::runtime_error&)
    {
        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 throw raised runtime_error, 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 boom, you printed the exception text instead of caught. If the program stops with no caught line, the catch may be missing. If the build fails about runtime_error, check #include <stdexcept>.

📊 throw and what the screen shows

Piece What the screen shows
First caught, because throw raises runtime_error and the catch prints that word
Last caught, because the program prints one line and returns
Rule throw raises an exception; catch handles std::runtime_error so the run continues
Screen caught

Try one change at a time. Temporarily print e.what() inside a catch that names the exception object, rebuild to see boom, then restore the checked catch that prints caught. Next, temporarily remove the catch and rebuild only long enough to see the uncaught stop, then restore the catch immediately. Each experiment changes one thing on purpose, so the screen shows either the exception text or the recovery word. Undo each change before the next one starts, so the file always returns to the checked workshop version with throw std::runtime_error("boom"); and catch printing caught once again after every single careful try back on disk again.
This page ends the throw tool and stops before the next one. The next page is files, which reads text from a file. The throw you have just written only shows raising runtime_error 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