TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 10 of 18 · Free

Exception Handling in C++ – try, catch, throw and std::optional

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Report errors with return values and std::optional
  • Use try, throw and catch to handle exceptions in C++
  • Create your own exception class and catch it by reference

A school fee app asks for the fee amount. Someone types -500 by mistake. Should the program print a wrong receipt, crash, or say clearly what went wrong? In this lesson you learn how C++ programs report and handle errors in a controlled way.

What happens in C++ when something goes wrong?

Some errors are not bugs in your code. The user types bad marks, a file is missing, or a class has zero students. Your program must notice these problems and react.

The oldest way is an error code. The function returns true or false to say if it worked. The real answer goes out through a reference parameter (you met references in Lesson 1).

The caller must check the result every time. If it forgets, the error is silently ignored. Try it: change the count of students to 4 and run again.

🧩 C++ — you can edit this code
Output
Error: the class has no students

How do try, catch and throw work in C++?

An exception is an object that a function throws when it cannot do its job. The keyword throw stops the function at once.

C++ then jumps to the nearest matching catch block. Code inside try after the throw is skipped. The catch block receives the thrown object.

runtime_error comes from the <stdexcept> header. Its what() function returns the message you gave it. This makes the error impossible to ignore: if nobody catches it, the program stops.

📄 Example to read — exceptions do not run in this browser compiler yet — output from g++ on our computer
#include <iostream>
#include <stdexcept>
using namespace std;

int checkFee(int amount) {
    if (amount < 0) {
        throw runtime_error("Fee cannot be negative");
    }
    return amount;
}

int main() {
    try {
        int a = checkFee(1500);
        cout << "Fee: " << a << "\n";
        int b = checkFee(-500);              // throws
        cout << "Fee: " << b << "\n";      // skipped

    } catch (const runtime_error& e) {
        cout << "Error: " << e.what() << "\n";
    }
    cout << "Program keeps running\n";
    return 0;
}
Output
Fee: 1500
Error: Fee cannot be negative
Program keeps running

💡 The second "Fee:" line is never printed: throw jumps straight to catch. Try it: change -500 to 800 and run again.

How do you catch different exception types in C++?

The standard library has a family of exception classes. All of them inherit from std::exception (inheritance was Lesson 3).

invalid_argument means bad input. out_of_range means a number or position is outside the allowed range. You can write several catch blocks; C++ uses the FIRST one whose type matches.

catch (...) with three dots catches anything. Put it last as a safety net. Always catch by const reference (const exception& e), so the object is not copied or cut down.

📄 Example to read — exceptions do not run in this browser compiler yet — output from g++ on our computer
#include <iostream>
#include <stdexcept>
using namespace std;

void bookSeat(int seat) {
    if (seat < 1 || seat > 72) {
        throw out_of_range("Seat must be 1 to 72");
    }
    if (seat % 8 == 0) {
        throw invalid_argument("Seat is reserved for staff");
    }
    cout << "Seat " << seat << " booked\n";
}

int main() {
    int requests[] = {12, 80, 16};
    for (int seat : requests) {
        try {
            bookSeat(seat);
        } catch (const out_of_range& e) {
            cout << "Range error: " << e.what() << "\n";
        } catch (const exception& e) {
            cout << "Other error: " << e.what() << "\n";
        }
    }
    return 0;
}
Output
Seat 12 booked
Range error: Seat must be 1 to 72
Other error: Seat is reserved for staff

How do you make your own exception class in C++?

You can create your own exception type by inheriting from runtime_error. Pass the message to the parent constructor.

When an exception leaves a function, C++ destroys the local objects of that function. Their destructors (Lesson 7) still run. This is called stack unwinding.

This is why C++ has no finally keyword: put clean-up code in destructors, and it runs whether there is an error or not. In the output, "Receipt closed" appears BEFORE the catch message.

📄 Example to read — exceptions do not run in this browser compiler yet — output from g++ on our computer
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

class LowBalance : public runtime_error {
public:
    LowBalance(const string& msg) : runtime_error(msg) {}
};
class Receipt {
public:
    Receipt()  { cout << "Receipt opened\n"; }
    ~Receipt() { cout << "Receipt closed\n"; }
};
void payCanteen(int balance, int price) {
    Receipt r;
    if (price > balance) {
        throw LowBalance("Need Rs " + to_string(price - balance) + " more");
    }
    cout << "Paid Rs " << price << "\n";
}
int main() {
    try {
        payCanteen(50, 30);
        payCanteen(50, 80);
    } catch (const LowBalance& e) {
        cout << "LowBalance: " << e.what() << "\n";
    }
    return 0;
}
Output
Receipt opened
Paid Rs 30
Receipt closed
Receipt opened
Receipt closed
LowBalance: Need Rs 30 more

How do you handle errors without exceptions using std::optional?

Sometimes "no answer" is a normal result, not a disaster. For example, searching for a roll number that is not in the list.

std::optional<int> (C++17, header <optional>) holds either an int or nothing. Return a value for success and nullopt for "no value". The caller checks with has_value() or if (result).

value_or(x) gives the value, or x when it is empty. Many teams use optional for expected problems and exceptions for rare, serious ones. Try it: search for roll number 7 and run again.

🧩 C++ — you can edit this code
Output
Roll number not found
With default: 91

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

try {
    cout << "A";
    throw 5;
    cout << "B";
} catch (int e) {
    cout << "C" << e;
}
cout << "D\n";

Question 2. out_of_range inherits from logic_error. What does this print?

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        throw out_of_range("Seat 99");
    } catch (const logic_error& e) {
        cout << "logic: " << e.what() << "\n";
    } catch (const out_of_range& e) {
        cout << "range: " << e.what() << "\n";
    }
    return 0;
}

Question 3. What does this print?

#include <iostream>
#include <optional>
using namespace std;

int main() {
    optional<int> score;
    cout << score.value_or(-1) << " " << score.has_value() << "\n";
    score = 42;
    cout << score.value_or(-1) << "\n";
    return 0;
}

🧩 Your challenge

Write a function readMarks that checks marks typed as text. It returns std::optional<int>: the number when the text is only digits and the value is 0–100, otherwise nullopt. Do NOT use stoi: in standard C++ it throws an exception for bad text, and exceptions do not run in this browser compiler. Expected output: 92 -> OK 92 1O0 -> invalid 105 -> invalid -> invalid 7 -> OK 7

Expected output :
92 -> OK 92
1O0 -> invalid
105 -> invalid
 -> invalid
7 -> OK 7
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    cout << "Checking fee...\n";
    throw runtime_error("Fee not paid");
    return 0;
}

terminate called after throwing an instance of 'std::runtime_error'

✅ Right

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    cout << "Checking fee...\n";
    try {
        throw runtime_error("Fee not paid");
    } catch (const exception& e) {
        cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

An exception that nobody catches calls std::terminate, which stops the whole program. Wrap risky code in try and catch the error where you can handle it.

❌ Wrong

#include <iostream>
#include <string>
using namespace std;

int main() {
    try {
        throw "Marks cannot be negative";
    } catch (const string& msg) {
        cout << "Error: " << msg << "\n";
    }
    return 0;
}

terminate called after throwing an instance of 'char const*'

✅ Right

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        throw invalid_argument("Marks cannot be negative");
    } catch (const exception& e) {
        cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

"text" in quotes is a const char*, not a std::string, so catch (const string&) never matches and the program stops. Throw a standard exception class instead.

❌ Wrong

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        throw out_of_range("Roll number 99 not found");
    } catch (exception e) {
        cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

Compiles and runs, but prints: Error: std::exception ⏎

✅ Right

#include <iostream>
#include <stdexcept>
using namespace std;

int main() {
    try {
        throw out_of_range("Roll number 99 not found");
    } catch (const exception& e) {
        cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

Catching by value copies only the base exception part (slicing), so your message is lost. Catch by const reference.

📌 Remember

  • Errors like bad input or missing data must be noticed and handled, not ignored.
  • throw stops a function; C++ jumps to the first matching catch block.
  • Standard exceptions (runtime_error, invalid_argument, out_of_range) come from <stdexcept>; what() gives the message.
  • Always catch by const reference, and put specific types before general ones.
  • Destructors still run when an exception passes through (stack unwinding).
  • std::optional is a simple way to say "no value" without exceptions.

Finished the quiz and the challenge?

Questions students ask

What is exception handling in C++?

It is a way to report and handle errors. A function throws an exception object when it cannot do its job. The nearest matching catch block handles it, and the program can carry on.

Does C++ have a finally block?

No. C++ uses destructors instead. Objects created inside the function are destroyed when an exception passes through, so clean-up code in a destructor always runs.

Should I use exceptions or error codes in C++?

Both are used. Exceptions are good for rare, serious errors that the caller must not ignore. Return values such as bool or std::optional suit expected cases like "not found". Some projects, such as many games, turn exceptions off completely.

Why don't exceptions run in the browser here?

The browser compiler is built without exception support. That is why the try/catch boxes are read-only and their output comes from g++. The optional examples run normally.