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>
#include <string>
using namespace std;
class Array {
private:
//array to hold 5 elements of type int
int elements[5];
public:
Array(){}
Array(int elements[]){
for(int i=0;i<5;i++){
this->elements[i]=elements[i];
}
}
~Array(){}
// Define a member function int Get(int index);Â
int Get(int index){
//if index is between 0 to 4 and throws an exception if index is out of bounds.
if(index<0 || index>=5){
throw exception("Index is out of bounds.");Â
}
return elements[index];
}
};
int main(){
//Catch the exception in the main program and print an error
try {
int elements[]={5,4,8,6,3};
Array _array(elements);
cout<<_array.Get(2)<<"\n";
cout<<_array.Get(4)<<"\n";
cout<<_array.Get(10)<<"\n";
}
catch (exception& exp) {
cout<<exp.what()<<"\n";
}
system("pause");
return 0;
}
Comments
Leave a comment