C++ Foundations·Practice drills 10

Drill 24: Compare — Exceptions and safety

Compare this example with a related lesson or language.

Intermediate 5 min read Lesson 244 of 300 Challenge included
What you will be able to do
  • Compare this example with a related lesson or language.

Practice task

Compare this example with a related lesson or language.

notes.cppC++
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>

class NotesFile {
public:
    explicit NotesFile(const std::string& path) : file_(path) {
        if (!file_.is_open()) {
            throw std::runtime_error("cannot open " + path);
        }
    }

    std::string read_line() {
        std::string line;
        if (!std::getline(file_, line)) {
            throw std::runtime_error("read failed");
        }
        return line;
    }

private:
    std::ifstream file_;
};

int clamp(int value, int low, int high) noexcept {
    if (value < low) return low;
    if (value > high) return high;
    return value;
}

void load() {
    try {
        NotesFile notes{"notes.txt"};
        std::cout << notes.read_line() << "\n";
    } catch (const std::exception& error) {
        std::cout << "error: " << error.what() << "\n";
    }
}
Your turn

Write your answer

Easy

Compare this example with a related lesson or language.

TEXT · starter
Your answer…
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 244 of 300 · 0% of course