Drill 12: Compare — Exceptions and safety
Compare this example with a related lesson or language.
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.
#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
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 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.