C++ Foundations·Practice drills 8

Drill 19: Change a value — Exceptions and safety

Describe what would change if you edited one value.

Intermediate 5 min read Lesson 194 of 300 Challenge included
What you will be able to do
  • Describe what would change if you edited one value.

Practice task

Describe what would change if you edited one value.

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

Describe what would change if you edited one value.

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 194 of 300 · 0% of course