WAP to show exception using try throw and catch block.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
//Handle error of size of array and out of bound exception
int sz;
int index;
do
{
try
{
cout<<"\nPlease, enter a size of array (0 - exit program): ";
cin>>sz;
if(sz==0)break;
if(sz<0)throw -1;//Handle catch(int a)
int *arr=new int[sz];
//Seed generator of random numbers
srand(static_cast<unsigned int>(time(0)));
//Fill array of sz elements and print it
cout<<"Our array: ";
for(int i=0;i<sz;i++)
{
arr[i]=rand();
cout<<arr[i]<<" ";
}
cout<<"\nPlease, enter an index of array to look value : ";
cin>>index;
if(index<0||index>=sz)
{
delete[] arr;//Free memory
throw "Out of bound";//Handle catch(const char* except)
}
cout<<"The value of index "<<index<<" is "<<arr[index];
delete[] arr;//Free memory
}
catch(int a)
{
cout<<"Error! Size of array must be integer and great than zero!";
}
catch(const char* except)
{
cout<<"Error! "<<except;
}
}while(true);
}
Comments
Leave a comment