thespeedracer38

Array class using ExceptionHandling

Apr 1st, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std;
  5.  
  6. #define CAP 10
  7. class Array{
  8.     int arr[CAP];
  9.     int size;
  10.     public:
  11.         Array(int=CAP);
  12.         ~Array(){ }
  13.         class InvalidSizeException{
  14.             int size;
  15.             public:
  16.                 InvalidSizeException(int size){
  17.                     InvalidSizeException::size = size;
  18.                 }
  19.                 void display(){
  20.                     cout << "InvalidSizeException" << endl;
  21.                     cout << size << ": exceeds the capacity " << CAP << endl;
  22.                 }
  23.         };
  24.         class ArrayIndexOutOfBoundsException{
  25.             int index;
  26.             public:
  27.                 ArrayIndexOutOfBoundsException(int index){
  28.                     ArrayIndexOutOfBoundsException::index = index;
  29.                 }
  30.                 void display(){
  31.                     cout << "ArrayIndexOutOfBoundsException for index " << index
  32.                         << endl;
  33.                 }
  34.         };
  35.         int& operator[](int);
  36. };
  37.  
  38. Array::Array(int size){
  39.     if(size <= 0 || size > CAP){
  40.         throw InvalidSizeException(size);
  41.     }
  42.     else{
  43.         Array::size = size;
  44.     }
  45. }
  46.  
  47. int& Array::operator[](int index){
  48.     if(index < 0 || index >= size){
  49.         throw ArrayIndexOutOfBoundsException(index);
  50.     }
  51.     return arr[index];
  52. }
  53.  
  54. int main() {
  55.     int size;
  56.     try{
  57.         cout << "Enter the size of the array: ";
  58.         cin >> size;
  59.         Array obj(size);
  60.         cout << "Input elements in the array" << endl;
  61.         for(int i = 0; i < size; i++){
  62.             cout << "arr[" << i << "] = ";
  63.             cin >> obj[i];
  64.         }
  65.         int index;
  66.         cout << "Enter the index location: ";
  67.         cin >> index;
  68.         cout << "Element at " << index << " is " << obj[index];
  69.     }
  70.     catch(Array::InvalidSizeException i){
  71.         i.display();
  72.     }
  73.     catch(Array::ArrayIndexOutOfBoundsException a){
  74.         a.display();
  75.     }
  76.     return 0;
  77. }
Add Comment
Please, Sign In to add comment