Drill 23: Change a value — Exceptions and safety
Describe what would change if you edited one value.
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.
#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
EasyWrite your answer
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 inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.