Embercode
✕
Object-Oriented ProgrammingQuick quiz

Exceptions

6 questions. Covers Exceptions in class design.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``cpp #include <iostream> #include <stdexcept> #include <string> class BankError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class FrozenError : public BankError { public: FrozenError() : BankError("frozen") {} }; void run(int n) { try { if (n == 1) throw FrozenError{}; if (n == 2) throw BankError("generic"); std::cout << "ok\n"; } catch (const FrozenError& e) { std::cout << "frozen handler: " << e.what() << "\n"; } catch (const BankError& e) { std::cout << "bank handler: " << e.what() << "\n"; } } int main() { run(0); run(1); run(2); } ``
  2. 2. Why must a derived catch block come before a base catch block?
  3. 3. Order the rules for writing a custom C++ exception class, from first to last.

    Use the arrows to put the steps in order.

    1. 1.Add fields for the extra data, and give them getter functions
    2. 2.Catch the exception by const reference
    3. 3.Pass the message to the base class, which stores it for what()
    4. 4.Inherit from a standard exception class, usually std::runtime_error
  4. 4. What does this program print? ``cpp #include <iostream> #include <stdexcept> class Account { public: explicit Account(int b) : balance_(b) {} void withdraw(int amount) { if (amount > balance_) throw std::runtime_error("short"); balance_ -= amount; } int balance() const { return balance_; } private: int balance_; }; int main() { Account a{100}; try { a.withdraw(30); a.withdraw(90); } catch (const std::runtime_error& e) { std::cout << e.what() << " " << a.balance() << "\n"; } } ``
  5. 5. The Email constructor throws when the text has no @. The program tries Email bad{"ana.example.com"}; inside a try block. Which statement is true?

4 question(s) left on this page.