c++ - Catching exception from out of index -


i have main file can not edit. there things done , writing classes suitable main file. v1 object instance of own vector class.

at point of main have line.

try {     // trying element at(4)     // should give error     cout << v1[4] << endl; } catch (const string & err_msg) {     cout << err_msg << endl; } 

my v1 vector's size "3" program crashing because going out of index. taking error ok here. how can exception cout line before program crashes ? , not allowed edit main code. need header files or class definitions. thanks.

without modifying main code, should write own vector class check bounds in operator[].

something like:

template <typename t> class myvector {   t *data;   int length;    ...    t &operator[](int i)   {     if (i < 0 || >= length)        throw std::string("out of bounds!"); //throw std::out_of_range;     else        return data[i];   }   ... }; 

otherwise if you're using std::vector, can use at instead of []:

returns reference element @ specified location pos. bounds checking performed, exception of type std::out_of_range thrown on invalid access.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -