I get an exception even if the code is inside a try / catch block

I wrote code that throws an exception if the given user input is invalid, so I put it in a try / catch block, but it still threw an exception. The code itself is quite long, so here is a simplified version of the code that also encounters an exception. The exception itself is clear, the position “3” does not exist, so naturally it throws an exception, but inside the try / catch block it must be caught, but it is not.

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (...)
    {

    }
}

Running this code throws the following exception, regardless of whether it is in a try / catch block.

Exception

I also tried to throw an exception ( const out_of_range&e), but that didn't help either. It just caused the same exception.

int main() {
    try
    {
        vector<string> test = vector<string>{ "a","b","c" };
        string value = test[3];
    }
    catch (const out_of_range&e)
    {

    }
}

Visual Studio, IDE ?

+6
3

, std::vector std::out_of_range, .at(). operator[] .

, - :

std::vector<int> myvector(10);
try {
    myvector.at(20)=100;      // vector::at throws an out-of-range
}
catch (const std::out_of_range& e) {
    std::cerr << "Out of Range error: " << e.what() << '\n';
}
+11

. .

, vector (index), .

+8

[] , ( undefined , , )

.at(). . cplusplus.com :

Strong guarantee: if an exception is thrown, there are no changes in the container.
It throws out_of_range if n is out of bounds.

Read: http://www.cplusplus.com/reference/vector/vector/operator[†/ http://www.cplusplus.com/reference/vector/vector/at/

Look at the bottom for safety exceptions.

+1
source

All Articles