Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
555 views
in Technique[技术] by (71.8m points)

c++ - Does "try-catch" catches run time error (especially Out of Range error)

I'm following an example code from Programming Principles and Practice Using C++ in one of the example for exception it shows this snippet of code

int main()
{
    try {
        vector<int> v; // a vector of ints
        for (int x; cin >> x; )
            v.push_back(x); // set values
        for (int i = 0; i <= v.size(); ++i) // print values
            cout << "v[" << i << "] == " << v[i] << '
';
    }
    catch (const out_of_range& e) {
        cerr << "Oops! Range error
";
        return 1;
    }
    catch (...) { // catch all other exceptions
        cerr << "Exception: something went wrong
";
        return 2;
    }
}

From what I understand it is suppose to catch out_of_range error and output "Oops! Range error". However, the Visual Studio 2019 shows this instead.

enter image description here

can someone explain why it shows me this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Does “try-catch” catches run time error (especially Out of Range error)?

No, in C++ most run time errors lead to Undefined Behavior, not exceptions. Only errors which explicitly throw exceptions can be caught.

std::vector<T>::operator[] does not specify that it throws an exception when you access out of bounds, it is just Undefined Behavior and anything can happen. It can even appear to work. When I try it here, there isn't any visible error : https://godbolt.org/z/Pcv9Gn8M9

If you want an exception on out of bounds access, std::vector<T>::at() does throw std::out_of_range.

For your test you should use v.at(i) instead of v[i]. Try it here : https://godbolt.org/z/szKxhjxhx.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...