Define a class Array which can hold 5 elements of type int. Define a member function int Get(int index); which returns the indexth element of the array if index is between 0 to 4 and throws an exception if index is out of bounds. Catch the exception in the main program and print an error.
#include <iostream>
using namespace std;
class Array{
private:
int elements[5] = {1,2,3,4,5};
public:
int Get(int index)
{
if(index>=0 && index<=4)
return elements[index];
throw exception();
}
};
int main()
{
Array myArray;
try{
cout << myArray.Get(5) << endl;
}
catch(exception e)
{
cout << "index out of bounds " << endl;
}
return 0;
}
Comments
Leave a comment