← Back to Question List
C++ Code Walkthrough #133
All the Pieces at Once
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>3#include <string>45class JobError : public std::runtime_error {6public:7 explicit JobError(const std::string& m) : std::runtime_error(m) {}8};910class RetryableError : public JobError {11public:12 explicit RetryableError(const std::string& m) : JobError(m) {}13};1415class Lock {16public:17 Lock() { std::cout << "lock\n"; }18 ~Lock() { std::cout << "unlock\n"; }19};2021void runJob(int id) {22 Lock lock;23 std::cout << "job " << id << "\n";24 if (id == 2) {25 throw RetryableError("busy");26 }27 if (id == 3) {28 throw JobError("corrupt");29 }30}3132void runWithLog(int id) {33 try {34 runJob(id);35 } catch (const JobError& e) {36 std::cout << "log: " << e.what() << "\n";37 throw;38 }39}4041int main() {42 for (int id = 1; id <= 3; id++) {43 try {44 runWithLog(id);45 std::cout << "job " << id << " ok\n";46 } catch (const RetryableError& e) {47 std::cout << "retry later: " << e.what() << "\n";48 } catch (const JobError& e) {49 std::cout << "abandon: " << e.what() << "\n";50 }51 }52 return 0;53}