Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- #define CAP 10
- class Array{
- int arr[CAP];
- int size;
- public:
- Array(int=CAP);
- ~Array(){ }
- class InvalidSizeException{
- int size;
- public:
- InvalidSizeException(int size){
- InvalidSizeException::size = size;
- }
- void display(){
- cout << "InvalidSizeException" << endl;
- cout << size << ": exceeds the capacity " << CAP << endl;
- }
- };
- class ArrayIndexOutOfBoundsException{
- int index;
- public:
- ArrayIndexOutOfBoundsException(int index){
- ArrayIndexOutOfBoundsException::index = index;
- }
- void display(){
- cout << "ArrayIndexOutOfBoundsException for index " << index
- << endl;
- }
- };
- int& operator[](int);
- };
- Array::Array(int size){
- if(size <= 0 || size > CAP){
- throw InvalidSizeException(size);
- }
- else{
- Array::size = size;
- }
- }
- int& Array::operator[](int index){
- if(index < 0 || index >= size){
- throw ArrayIndexOutOfBoundsException(index);
- }
- return arr[index];
- }
- int main() {
- int size;
- try{
- cout << "Enter the size of the array: ";
- cin >> size;
- Array obj(size);
- cout << "Input elements in the array" << endl;
- for(int i = 0; i < size; i++){
- cout << "arr[" << i << "] = ";
- cin >> obj[i];
- }
- int index;
- cout << "Enter the index location: ";
- cin >> index;
- cout << "Element at " << index << " is " << obj[index];
- }
- catch(Array::InvalidSizeException i){
- i.display();
- }
- catch(Array::ArrayIndexOutOfBoundsException a){
- a.display();
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment