โ† All CPP Flashcard Decks

Exception Handling & Error Management Flashcards

7 cards from real CPP practice questions. Tap to flip, then mark Knew It or Still Learning โ€” missed cards come back until you master them.

Read the first 7 Exception Handling & Error Management flashcards as text
  1. What happens when an exception is thrown inside a destructor that is already executing due to stack unwinding?

    Answer: std::terminate() is called

    If a destructor throws while another exception is being propagated (stack unwinding), std::terminate() is called because two exceptions cannot be active simultaneously.

  2. Which of the following correctly creates a custom exception class that follows best practices?

    Answer: class MyEx : public std::exception { public: const char* what() const noexcept override { return "error"; } };

    Best practice is to inherit publicly from std::exception and override what() as const noexcept to match the base class contract.

  3. What does the noexcept specifier guarantee when applied to a function?

    Answer: The compiler optimizes the function assuming no exceptions will propagate out

    noexcept tells the compiler no exceptions will propagate out, enabling optimizations; if one does, std::terminate() is called.

  4. What is the output of: try { throw 42; } catch (double d) { cout << "double"; } catch (...) { cout << "other"; }

    Answer: other

    An int literal 42 does not match catch(double), so the catch-all handler catch(...) executes.

  5. Which function can be used to rethrow the currently active exception inside a catch block?

    Answer: throw;

    A bare throw; statement inside a catch block rethrows the currently active exception preserving its original type.

  6. What is std::exception_ptr used for?

    Answer: Storing and transporting exceptions across threads

    std::exception_ptr captures an exception with std::current_exception() and allows rethrowing it later, even in a different thread.

  7. In a catch clause, what is the advantage of catching by reference (catch(std::exception& e)) over catching by value?

    Answer: It prevents object slicing when catching derived exceptions through a base reference

    Catching by reference prevents slicing, ensuring the derived type's what() and virtual methods are called correctly.