std::out_of_range getting thrown

So after compiling my program with no errors, I try to run a query and the terminal tells me:

1
2
3
terminate called after throwing an instance of 'std::out_of_range' 
what(): basic_string::replace 
Aborted (core dumped)


Now, I understand the out_of_range error is getting thrown after having called the replace() method, but how do I prevent terminate from being called? I've tried this and it doesn't work:

1
2
3
4
5
6
try{
mystring.replace(beginSpace, range, fill);
}
catch(out_of_range& oor){
  cerr << "NOPE!" << endl;
}


I've also tried wrapping the part inside the main() function where this function would get called as such:

1
2
3
4
5
6
7
8
9
10
11
12
13
int main(){

  someClass sc = someClass();
  try{
    sc.doStuff()

  }
  catch(out_of_range& oor){
    cout << "DIDNT WORK!" << endl;
  } 

return 0;
}


I've also made sure to #include <stdexcept>
What output do you get for the following?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>
#include <stdexcept>

int main()
{
    std::string s ;

    try {
        s.replace(1, 10, "replacement") ;
        std::cout << "s: " << s << '\n' ;
    }

    catch (std::out_of_range& ex)
    {
        std::cout << "Exception caught!\n" << ex.what() << '\n' ;
    }
}
Topic archived. No new replies allowed.