← Back to Question List
C++ Quiz #153
Check First or Catch Later
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>45int main() {6 std::vector<int> prices = {5, 8, 13};7 std::size_t index = 7;89 if (index < prices.size()) {10 std::cout << "checked: " << prices[index] << "\n";11 } else {12 std::cout << "checked: no such item\n";13 }1415 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}