AlgoDaily

Exception Handling

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Your Safety Net

Welcome to the final lesson

You have traveled from Introduction to Programming all the way through Object-Oriented Programming. You can now write programs with variables, input/output, control flow, functions, arrays, strings, pointers, references, and classes.

Now we add one final professional habit: handling problems gracefully.

Real programs hit unexpected situations:

  • A user types letters when you expected a number
  • A file is missing
  • A basketball score calculation divides by zero
  • A home renovation estimate gets a negative number of paint cans
  • An object receives data that does not make sense

Exception handling gives your program a controlled way to say: “Something went wrong, but we can respond instead of crashing mysteriously.”

Your Safety Net

What Exceptions Do

The basic idea

An exception is a signal that something unusual or unsafe happened while the program was running.

Instead of pretending everything is fine, a function can throw an exception. Somewhere else, the program can catch it and decide what to do.

Think of it like an electrical breaker in a house:

  • Normal flow: electricity keeps moving
  • Dangerous situation: breaker trips
  • Safe response: you inspect and fix the problem

In C++, exception handling usually uses three keywords:

  • try: run code that might fail
  • throw: signal a problem
  • catch: handle the problem
try block
   |
   | normal path
   v
continues program

if problem happens:
   throw exception ---> catch block ---> recover or report

What Exceptions Do

Try And Catch

A first exception example

Here is a small program that divides two numbers. Division by zero is not safe, so the function throws an exception when the denominator is 0.

Notice the separation of responsibilities:

  • The function detects the problem
  • The try block calls the function
  • The catch block explains what went wrong

This keeps the program from ending in a confusing way.

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

double divide(double top, double bottom) {
    if (bottom == 0) {
        throw runtime_error("Cannot divide by zero.");
    }
    return top / bottom;
}

int main() {
    try {
        cout << "10 / 2 = " << divide(10, 2) << endl;
        cout << "10 / 0 = " << divide(10, 0) << endl;
        cout << "This line will not run after the exception." << endl;
    } catch (runtime_error& error) {
        cout << "Problem caught: " << error.what() << endl;
    }

    cout << "Program kept running safely." << endl;
    return 0;
}
```

Spot The Handler

In C++ exception handling, which keyword names the block that responds to an exception?

Throw From Functions

Functions can protect their promises

Back in Functions, you learned that functions package useful work behind a name. With exceptions, a function can also protect itself from impossible or invalid input.

For example, a renovation estimate should not accept a negative number of paint cans. If that happens, the function can throw an exception instead of returning a fake answer.

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

double paintCost(int cans, double pricePerCan) {
    if (cans < 0) {
        throw invalid_argument("Number of cans cannot be negative.");
    }
    return cans * pricePerCan;
}

int main() {
    int testCans[] = {3, -1, 5};

    for (int cans : testCans) {
        try {
            cout << cans << " cans cost $" << paintCost(cans, 28.50) << endl;
        } catch (invalid_argument& error) {
            cout << "Bad estimate input: " << error.what() << endl;
        }
    }

    cout << "Estimate checks complete." << endl;
    return 0;
}
```

Exceptions Stop Flow

True or false: When an exception is thrown inside a try block, C++ skips the remaining statements in that try block and looks for a matching catch block.

Standard Exceptions

C++ already has common exception types

C++ provides standard exception classes in headers like <stdexcept> and <exception>.

Common ones include:

  • runtime_error: something failed while the program was running
  • invalid_argument: a function received unacceptable input
  • out_of_range: code tried to access something outside its valid range

Many standard library tools can throw exceptions too. For example, vector::at() checks bounds and can throw out_of_range.

```cpp
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;

int main() {
    vector<string> playlist = {"drums", "guitar", "piano"};

    try {
        cout << "First instrument: " << playlist.at(0) << endl;
        cout << "Fourth instrument: " << playlist.at(3) << endl;
    } catch (out_of_range& error) {
        cout << "Playlist problem: index was outside the valid range." << endl;
    }

    cout << "Music app did not crash." << endl;
    return 0;
}
```

Fill The Keyword

Complete the sentence:

To signal that something went wrong, C++ code can use the keyword _____.

Use Exceptions Wisely

Good exception habits

Exceptions are powerful, but they should be used thoughtfully.

Use exceptions for unusual problems, not ordinary choices. For example:

Good use:

  • A required file cannot be opened
  • A function receives impossible input
  • An object cannot be safely created
  • A checked array access goes out of range

Usually not a good use:

  • Replacing every if statement
  • Ending a normal loop
  • Handling expected menu choices

A helpful rule: if the situation is part of normal program logic, use control flow from Control Flow. If the situation means “the normal promise of this function cannot be safely completed,” an exception may fit.

Use Exceptions Wisely

Course Wrap Up

You now have the beginner-to-expert foundation

This final lesson completes the course journey.

You started by learning what programming is. Then you set up your tools, stored data with variables, communicated with input/output, made decisions with control flow, organized work with functions, grouped data with arrays and strings, understood memory through pointers and references, modeled real-world things with classes, and now protected your programs with exception handling.

That is a serious C++ foundation.

What you can build now

You are ready to create small real-world programs such as:

  • A home renovation cost calculator
  • A basketball stat tracker
  • A music playlist organizer
  • An electronics parts inventory
  • A simple class-based simulation or tool
Final mindset

A good C++ programmer does not just write code that works once. They write code that is clear, organized, and prepared for things going wrong.

That is what exception handling adds: resilience.

Keep building, keep breaking things safely, and keep improving one program at a time.

Course Wrap Up

Open interactive view →