LearnFrenzy
Sign in Take a free test

Exception Handling · Exercise 2 of 4

Exception Handling Predict the Output

  • 20 questions
  • Page 2 of 2
  • Answers explained
0Attempted
0Correct
0Wrong
Directions

Read each C++ program and choose what it prints. Every program was compiled and run on a 64-bit system, so the answers are the real output.

Question 11 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>
#include <string>

class HttpError : public std::runtime_error {
    int status_;
public:
    HttpError(int s, const std::string& msg) : std::runtime_error(msg), status_(s) {}
    int status() const noexcept { return status_; }
    bool retryable() const noexcept { return status_ >= 500; }
};

void fetch(int code) { if (code != 200) throw HttpError(code, "HTTP " + std::to_string(code)); }

int main() {
    int retries = 0;
    for (int code : {200, 404, 503, 500}) {
        try { fetch(code); std::cout << "ok "; }
        catch (const HttpError& e) {
            std::cout << e.what() << (e.retryable() ? "(retry) " : " ");
            retries += e.retryable();
        }
    }
    std::cout << retries << '\n';
    return 0;
}
A ok HTTP 404 HTTP 503(retry) HTTP 500(retry) 2
B ok HTTP 404(retry) HTTP 503(retry) HTTP 500(retry) 3
C HTTP 200 HTTP 404 HTTP 503 HTTP 500 2
D ok HTTP 404 HTTP 503(retry) HTTP 500 1
Question page & discussion
Question 12 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <string>
#include <utility>

void a() noexcept {}
void b() {}
void c() noexcept(false) {}
template <typename T> void d(T) noexcept(sizeof(T) <= 8) {}
struct S { ~S() {} S(S&&) = default; std::string s; };

int main() {
    std::cout << noexcept(a()) << noexcept(b()) << noexcept(c()) << noexcept(d(1)) << noexcept(d(std::string()))
              << noexcept(std::declval<S&>().~S()) << noexcept(1 + 2) << '\n';
    return 0;
}
A 1001011
B 1001111
C 1000011
D 1101011
Question page & discussion
Question 13 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>

std::map<std::string, int> prices{{"pen", 20}, {"ink", 45}};

void apply(const std::vector<std::pair<std::string, int>>& changes) {
    auto next = prices;
    for (const auto& [item, p] : changes) {
        if (p <= 0) throw std::invalid_argument(item + " price must be positive");
        next[item] = p;
    }
    prices.swap(next);
}

int main() {
    apply({{"pen", 25}});
    try { apply({{"ink", 50}, {"bag", -1}}); }
    catch (const std::exception& e) { std::cout << e.what() << '\n'; }
    for (const auto& [k, v] : prices) std::cout << k << '=' << v << ' ';
    std::cout << '\n';
    return 0;
}
A bag price must be positive ink=45 pen=25
B bag price must be positive ink=50 pen=25
C bag price must be positive bag=-1 ink=50 pen=25
D ink=45 pen=20
Question page & discussion
Question 14 Easy

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>
#include <vector>

int reciprocal_percent(int x) {
    if (x == 0) throw std::domain_error("zero");
    return 100 / x;
}

int main() {
    std::vector<int> in{4, 0, 5, 0, 20};
    int ok = 0;
    for (int x : in) {
        try { std::cout << reciprocal_percent(x) << ' '; ++ok; }
        catch (const std::domain_error&) { std::cout << "- "; }
    }
    std::cout << "(" << ok << " ok)\n";
    return 0;
}
A 25 - 20 - 5 (3 ok)
B 25 (1 ok)
C 25 - 20 - 5 (5 ok)
D 25 0 20 0 5 (5 ok)
Question page & discussion
Question 15 Hard

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <exception>
#include <iostream>
#include <stdexcept>

void read_file() { throw std::runtime_error("permission denied"); }
void load_config() {
    try { read_file(); }
    catch (...) { std::throw_with_nested(std::runtime_error("cannot load config")); }
}
void start_app() {
    try { load_config(); }
    catch (...) { std::throw_with_nested(std::runtime_error("startup failed")); }
}

void report(const std::exception& e, int level = 0) {
    std::cout << level << ':' << e.what() << ' ';
    try { std::rethrow_if_nested(e); }
    catch (const std::exception& inner) { report(inner, level + 1); }
}

int main() {
    try { start_app(); } catch (const std::exception& e) { report(e); }
    std::cout << '\n';
    return 0;
}
A 0:startup failed 1:cannot load config 2:permission denied
B 0:permission denied 1:cannot load config 2:startup failed
C 0:startup failed
D 0:startup failed 1:permission denied
Question page & discussion
Question 16 Hard

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <exception>
#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<std::exception_ptr> errors;
    for (int job = 1; job <= 4; ++job) {
        try {
            if (job % 2 == 0) throw std::runtime_error("job " + std::to_string(job) + " failed");
        } catch (...) {
            errors.push_back(std::current_exception());     // keep it for later
        }
    }
    std::cout << errors.size() << " errors: ";
    for (const auto& p : errors) {
        try { std::rethrow_exception(p); }
        catch (const std::exception& e) { std::cout << '[' << e.what() << "] "; }
    }
    std::cout << '\n';
    return 0;
}
A 2 errors: [job 2 failed] [job 4 failed]
B 4 errors: [job 1 failed] [job 2 failed] [job 3 failed] [job 4 failed]
C 2 errors:
D 0 errors:
Question page & discussion
Question 17 Hard

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>
#include <string>

int parse_port(const std::string& s) {
    int p = std::stoi(s);
    if (p <= 0 || p > 65535) throw std::out_of_range("port out of range");
    return p;
}

struct Server {
    int port;
    explicit Server(const std::string& s)
    try : port(parse_port(s)) {
        std::cout << "listening on " << port << '\n';
    } catch (const std::exception& e) {
        std::cout << "Server init failed: " << e.what() << '\n';
        // the exception is rethrown automatically at the end of this handler
    }
};

int main() {
    for (std::string s : {"8080", "99999"}) {
        try { Server srv(s); }
        catch (const std::out_of_range&) { std::cout << "main: caught out_of_range\n"; }
    }
    return 0;
}
A listening on 8080 Server init failed: port out of range main: caught out_of_range
B listening on 8080 Server init failed: port out of range
C listening on 8080 main: caught out_of_range
D Server init failed: port out of range main: caught out_of_range
Question page & discussion
Question 18 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <mutex>
#include <stdexcept>

std::mutex m;
int balance = 100;

void withdraw(int x) {
    std::lock_guard<std::mutex> lock(m);
    if (x > balance) throw std::runtime_error("insufficient");
    balance -= x;
}

int main() {
    try { withdraw(150); } catch (const std::exception& e) { std::cout << e.what() << ' '; }
    bool free_again = m.try_lock();          // would fail if the exception had left it locked
    std::cout << free_again << ' ';
    if (free_again) m.unlock();
    withdraw(30);
    std::cout << balance << '\n';
    return 0;
}
A insufficient 1 70
B insufficient 0 70
C insufficient 1 100
D The program deadlocks
Question page & discussion
Question 19 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <typeinfo>

struct Animal { virtual ~Animal() = default; };
struct Dog : Animal { const char* bark() const { return "Woof"; } };
struct Cat : Animal {};

const char* try_bark(const Animal& a) {
    try {
        return dynamic_cast<const Dog&>(a).bark();
    } catch (const std::bad_cast&) {
        return "(not a dog)";
    }
}

int main() {
    Dog d; Cat c;
    const Animal* p = &c;
    std::cout << try_bark(d) << ' ' << try_bark(c) << ' ' << (dynamic_cast<const Dog*>(p) == nullptr) << '\n';
    return 0;
}
A Woof (not a dog) 1
B Woof Woof 1
C Woof (not a dog) 0
D The program crashes
Question page & discussion
Question 20 Medium

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <optional>
#include <string>
#include <variant>

int main() {
    std::optional<int> none;
    std::variant<int, std::string> v = 5;
    int caught = 0;
    try { std::cout << none.value(); } catch (const std::bad_optional_access&) { ++caught; std::cout << "no value "; }
    try { std::cout << std::get<std::string>(v); } catch (const std::bad_variant_access&) { ++caught; std::cout << "wrong type "; }
    std::cout << none.value_or(-1) << ' ' << std::get<int>(v) << ' ' << caught << '\n';
    return 0;
}
A no value wrong type -1 5 2
B no value -1 5 1
C 0 wrong type -1 5 1
D The program crashes
Question page & discussion
Up next · Exercise 3Find the Error10 questions

Ready to test your Programming?

Timed online tests with instant scores and explanations.

Search LearnFrenzy

Esc

Quick links