ROGRAM –10
AIM: - Write a program to raise an exception if any attempt is made to refer to an element
whose index is beyond the array size.
ALGORITHM:-
CODE:
#include <iostream>
#include <stdexcept>
class ArrayWithBoundsCheck {
private:
int* array;
int size;
public:
ArrayWithBoundsCheck(int size) : size(size) {
array = new int[size];
}
~ArrayWithBoundsCheck() {
delete[] array;
}
int& operator[](int index) {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of bounds");
}
return array[index];
}
};
int main() {
cout<<"ANSH BALGOTRA"<<endl;
const int arraySize = 5;
ArrayWithBoundsCheck myArray(arraySize);
try {
// Accessing within bounds
for (int i = 0; i < arraySize; ++i) {
myArray[i] = i * 10;
}
// Accessing within bounds
std::cout << "Accessing within bounds:" << std::endl;
for (int i = 0; i < arraySize; ++i) {
std::cout << "myArray[" << i << "] = " << myArray[i] << std::endl;
}
// Accessing out of bounds (uncomment to see the exception)
int value = myArray[arraySize]; // This will throw an exception
} catch (const std::out_of_range& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
OUTPUT: