CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #141

A Loop That Catches and Continues

easyExceptions

The try/catch sits INSIDE the loop body. What is printed?

📄 Code

1#include <iostream>
2#include <stdexcept>
3#include <vector>
4 
5int half(int n) {
6 if (n % 2 != 0) {
7 throw std::invalid_argument("odd");
8 }
9 return n / 2;
10}
11 
12int main() {
13 std::vector<int> values = {8, 5, 12};
14 int failures = 0;
15 for (int v : values) {
16 try {
17 int result = half(v);
18 std::cout << result << "\n";
19 } catch (const std::invalid_argument&) {
20 failures++;
21 std::cout << "skipped " << v << "\n";
22 }
23 }
24 std::cout << "failures: " << failures << "\n";
25 return 0;
26}