Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views4 pages

Program 10

The document describes a C++ program that defines a class called ArrayWithBoundsCheck to represent an array. The class checks that any access to elements uses a valid index that is within the bounds of the array size, and throws an out_of_range exception if an invalid index is used. The main function demonstrates accessing elements within the bounds of the array without errors, and shows that accessing beyond the bounds throws the exception as expected.

Uploaded by

Ansh Balgotra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views4 pages

Program 10

The document describes a C++ program that defines a class called ArrayWithBoundsCheck to represent an array. The class checks that any access to elements uses a valid index that is within the bounds of the array size, and throws an out_of_range exception if an invalid index is used. The main function demonstrates accessing elements within the bounds of the array without errors, and shows that accessing beyond the bounds throws the exception as expected.

Uploaded by

Ansh Balgotra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

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:

You might also like