I need to learn C++ basics for a research project, and I’m experimenting with error/exception handling. I did use the throw command successfully to anticipate on events that might occur (like divide by zero), but I cannot figure out how to catch unanticipated exceptions. Take this example code:
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
void arrayOutOfBound()
{
int a[3] = {1, 2, 3};
try
{
cout << "This should not display: " << a[5] << endl;
}
catch(runtime_error &e)
/* catch(exception &e) // also does not work */
{
cout << "Error: " << e.what() << endl;
}
}
int main()
{
arrayOutOfBound();
}
I guess I have to use throw statements somewhere, but suppose I really did not know that a[5] wouldn’t work (or the user entered this index and I did not check for the array size), then how can I prevent the program from crashing? (as this happens in the Visual C++ Express 2010 debugger)
Note: if I would do try { int result = a[5]; } first, outside the block, and try to use cout << result at the end, the program does not compile. The compiler is trying to help me, but therefore I cannot try the exception handling.
You simply can’t. An out of bounds access to an array causes undefined behavior in C++, it won’t throw an exception. When you are lucky enough, you get a crash.