Throw catch on vector.erase() fails to prevent crash?

1
2
try { file_parts.erase(file_parts.begin()+i-1, file_parts.begin()+i+1); }
catch (exception e) { return false; }


I'm trying to erase indexes that don't exist and the "return false" never gets triggerd because the program crashes at "try". What am I doing wrong?

runnable code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
  vector<string> file_parts{"folder1","folder2","folder3"};
  int i = 1000;
  try { file_parts.erase(file_parts.begin()-i); }
  catch (exception e) { cout << "FAIL!!!" << endl; }
  for(auto s:file_parts) cout << s << "/";;
  cout << endl << "program finished";
}
Last edited on
What am I doing wrong?

this:
I'm trying to erase indexes that don't exist


And yes, vector::erase does not throw any exceptions when called with invalid iterators: http://en.cppreference.com/w/cpp/container/vector/erase "The iterator pos must be valid and dereferenceable" http://www.cplusplus.com/reference/vector/vector/erase "An invalid position or range causes undefined behavior."
-- it is the responsibility of the caller to satisfy preconditions.
Last edited on
ah ok thanks. Now I know to RTFM :)
Topic archived. No new replies allowed.