WAP to handle array out of Bounds Exception
Objective
Write a C++ program to manually handle an Array Out of Bounds Exception.
Algorithm / Approach
- Define an array of 5 elements.
- Read an index number
xto search. - Check if the requested index is greater than or equal to the array size (
x >= 5). - If true,
throwa string warning. - Catch the warning in
main()and display it gracefully instead of crashing.
main.cpp
#include<iostream>
using namespace std;
class Test {
public :
void find(int x) {
int arr[5] = {1,2,3,4,5};
if(x>=5){
throw "Index out of Bounds ";
}
cout<<"Element= "<< arr[x]<< endl;
}
};
int main() {
Test t;
int x;
cout<<"Enter Index no. to search ";
cin>>x;
try{
t.find(x);
}
catch(const char *str) {
cout<< str;
}
return 0;
}
Expected Output
Enter Index no. to search 6 Index out of Bounds
Explanation of the Program
- Unlike Java or C#, C++ arrays are just raw pointers and do NOT automatically check boundaries. If you request index 100 of a 5-element array, C++ will blindly attempt to read random garbage data from memory instead of crashing!
- Therefore, if you want "Out of Bounds" protection in C++, you must manually write the
ifstatements to check the boundaries andthrowthe exceptions yourself.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)