Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to handle array out of Bounds Exception

C++ Code Example — Exception Handling

ADVERTISEMENT

WAP to handle array out of Bounds Exception

Objective

Write a C++ program to manually handle an Array Out of Bounds Exception.

Algorithm / Approach

  1. Define an array of 5 elements.
  2. Read an index number x to search.
  3. Check if the requested index is greater than or equal to the array size (x >= 5).
  4. If true, throw a string warning.
  5. 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 if statements to check the boundaries and throw the exceptions yourself.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT