Jonas
Jonas

Reputation: 311

C++: accessing an array of unknown size by using try/catch

I was using Java for quite a time and had to move back to C++. I didn't use try/catch in C++ so much before, and now when I work again, I encountered probably a very silly problem.

I have an array of unknown size and want to cout all the numbers that exist in it. However, I do not want to use C++ vectors, which would give me an exact size. What I tried is to have a for loop that is not supposed to end by itself. I want to break it when an exception is thrown, which I would catch and handle the problem. However, it doesn't work and doesn't throw an exception.

Can anyone enlighten me? :) Thank you.

    for(int i = 0; i < 1000; i++) {
       try {
           cout << symbols[i] << " ";
       } catch (int ex) {
           cout << "thrown";
           break;
       }
}

Upvotes: 1

Views: 3440

Answers (2)

Ed Swangren
Ed Swangren

Reputation: 124752

Undefined behavior means that anything may happen. It certainly does not mean "an exception of the type X will be thrown". Your program is left in an undefined state. Even if you could catch it what would you do to fix it? There's nothing you could possibly do, your program is borked.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206596

Accessing an array beyond its bounds gives undefined behavior not an exception.
An Undefined behavior means that the program ceases to be a valid C++ program and may show any behavior, correct or incorrect but you cannot rely on it to be consistent.
You need to keep track of the size by yourself and loop by using that size or throw an exception as you might want to.

Upvotes: 6

Related Questions