CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #124

A Family of Errors, Caught in Order

mediumExceptions

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <stdexcept>
3#include <string>
4 
5class SensorError : public std::runtime_error {
6public:
7 explicit SensorError(const std::string& m) : std::runtime_error(m) {}
8};
9 
10class Disconnected : public SensorError {
11public:
12 Disconnected() : SensorError("sensor disconnected") {}
13};
14 
15class OutOfRange : public SensorError {
16public:
17 OutOfRange() : SensorError("reading out of range") {}
18};
19 
20int read(int sample) {
21 if (sample < 0) {
22 throw Disconnected();
23 }
24 if (sample > 100) {
25 throw OutOfRange();
26 }
27 return sample;
28}
29 
30int main() {
31 int samples[] = {20, -1, 150, 99};
32 for (int sample : samples) {
33 try {
34 int value = read(sample);
35 std::cout << "reading " << value << "\n";
36 } catch (const Disconnected& e) {
37 std::cout << "reconnect: " << e.what() << "\n";
38 } catch (const SensorError& e) {
39 std::cout << "sensor: " << e.what() << "\n";
40 }
41 }
42 return 0;
43}

🎯 Your Answer