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 #153

Check First or Catch Later

mediumExceptions

Both halves print the same words for index 7. What is the real difference between checking with if and catching the exception from at()?

📄 Code

1#include <iostream>
2#include <stdexcept>
3#include <vector>
4 
5int main() {
6 std::vector<int> prices = {5, 8, 13};
7 std::size_t index = 7;
8 
9 if (index < prices.size()) {
10 std::cout << "checked: " << prices[index] << "\n";
11 } else {
12 std::cout << "checked: no such item\n";
13 }
14 
15 try {
16 int value = prices.at(index);
17 std::cout << "caught: " << value << "\n";
18 } catch (const std::out_of_range&) {
19 std::cout << "caught: no such item\n";
20 }
21 return 0;
22}