Answer to Question #272521 in C++ for vjhvv5

Question #272521

WAP to show exception using try throw and catch block.


1
Expert's answer
2021-12-03T06:28:03-0500
#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);
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS