4

I am trying to use a standard exception class in c++ like:

#include <iostream>
#include <exception>
using namespace std;
int main(){
    int a[6]={12,3,2,4,5,6};
    int n=6;
    try{
     cout<<a[6]<<"  ";

    }
    catch(std::exception & exc)
     {
         cout<<exc.what();

     }

     return 0;  
    }

But instead of showing me the error - "out of index" ,it throws a run time error, saying that the "variable a is uninitialized" ,why? I have declared it as an array and make initialization of it. Please give me some advise why it does so?

1
  • Catch exception as const lvalue reference (const std::exception& ex) if you don't need to modify it. Commented Oct 5, 2011 at 13:53

5 Answers 5

14

Accessing a[6] is undefined behaviour, since the only valid indices for a are 0..5.

You shouldn't expect a[6] to perform any bounds checking, much less throw a C++ exception on out-of-bounds array access.

If do you want automatic bounds checking, make a into std::vector<int> and use a.at(index) to access its elements.

Sign up to request clarification or add additional context in comments.

Comments

4

A standard array does not check the bounds of your access. If you want a bound checking array you'd either use boost/std::array or std::vector and use the bound safe access function at().

Comments

2

You've declared a to be an array of six elements; the legal indexes run from 0 to 5. The result of the expression a[6] is undefined behavior -- program termination is (in this case) the result. Nowhere does it say that illegal array access will throw an exception -- this is not Java!

Comments

2

c++ does not check array sizes, so there is no exception thrown. If you want this check, you have to use a STL container like std::vector.

Comments

2

C++ exceptions are not meant to be used to catch programming errors. They are there for run time errors like unable to open a file etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.