Search code examples
c++vectortry-catch

Loop breaks after exception is catched


The for loop breaks after i=-1, And sum is 0.

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<int> vec{0, 1, 2, 3, 4};
    int sum = 0;
    
    for (int i = -1; i < vec.size(); i++) {
        try {
            throw vec.at(i);
        } catch (int x) {
            sum += x;
        } catch (...) {
            cout << "Exception Handled" << endl;
        }
    }

    cout << sum << endl;
    return 0;
}

The sum should be 10. And accesing index -1 should be catched.


Solution

  • vec.size() returns an unsigned integer type (usually std::size_t).

    You are comparing a signed integer i to an unsigned integer size(), so the compiler will convert the value of i to an unsigned type when comparing it to the value of size(). And -1 converts to a VERY LARGE unsigned value (see: What happens if I assign a negative value to an unsigned variable?), which in this case is the maximum value that size_t can hold.

    Since that converted value is larger than the actual size() value, the expression i < vec.size() evaluates as false on the 1st iteration, causing your loop to exit immediately without ever entering its body at all.