You can use try/catch to catch exceptions. The std::string at function will throw a out_of_range error if you try to use an illegal index:
std::string S = "Hello World"; try { std::string::size_type i = 0; while(1) { std::cout << S.at(i++); } } catch(std::out_of_range e) { std::cout << " The end!" << std::endl; std::cout << "What:" << e.what() << std::endl; }Notice that the [ ] operator does not throw an exception, the result is undefined if you try to use an illegal index.
You can define you own exception:
class MyException { public: MyException(std::string aWhat) : what(aWhat) {} std::string what; };To use it:
void Print(int x) { if(x > 10) throw MyException("At the end"); std::cout << x << std::endl; } int main() { try { int i = 0; while(1) Print(i++); } catch(MyException Except) { std::cout << Except.what << std::endl; } }