Chapter 9 · Error Detection and Handling
Practice · Chapter 9

Error Detection and Handling

Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.

9.3 — Common semantic errors in C++

predict

What does integer division produce here?

The variable rate is declared as double. What does the program print?

C++
#include <iostream>

int main()
{
    int passed = 7;
    int total  = 10;

    double rate = passed / total;

    std::cout << rate << '\n';
    return 0;
}
Choose the output
predict

Assignment inside an if condition

What does this program print? Look carefully at the operator inside the if.

C++
#include <iostream>

int main()
{
    int x { 0 };

    if (x = 5)
        std::cout << "branch taken, x = " << x << '\n';
    else
        std::cout << "branch skipped, x = " << x << '\n';

    return 0;
}
Choose the output

9.5 — std::cin and handling invalid input

fix

Fix the cin recovery order

The function reads one int from std::cin and should return the value on success or -1 on failure. The snapshot and clear() are in the wrong order — fix it.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

9.6 — Assert and static_assert

fix

Fix clampToRange: in-range values return wrong result

The function compiles and handles out-of-range inputs correctly, but returns the wrong value when the input is already inside [lo, hi]. Fix it.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

9.4 — Detecting and handling errors

write

Write isValidQuantity

Implement the function so all tests pass. Valid quantities are integers in the inclusive range [1, 999].

student.cppeditable

Edit student.cpp, then Run to check it against the tests.