LearnFrenzy
Sign in Take a free test

Exception Handling · Predict the Output · Question 10

vector::at throws std::out_of_range Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<int> v{10, 20, 30};
    int found = 0, errors = 0;
    for (std::size_t i : {0u, 2u, 3u, 7u}) {
        try { found += v.at(i); }
        catch (const std::out_of_range&) { ++errors; }
    }
    std::cout << found << ' ' << errors << '\n';
    return 0;
}
  • A 40 2 Correct
  • B 60 1
  • C 40 0
  • D 30 2
Correct Answer: Option A

at() checks the index and throws for 3 and 7; operator[] would not check (undefined behaviour).

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links