Add Try/Catch error checking To make sure that the user enters valid values in your program. To catch negative values passed to constructor. To catch if not enough memory is available for list. (Hint: bad_alloc)

Answer :

Answer:

int main()

{

 cout<<"Enter the size of array\n";

 int n;

 try{

 cin>>n;//get size of array

 if (n > 0){

 List list;//make object of list class

 try{

     list.init(n);//initialize the list

     list.fillData();//fill the data

     list.print();//print the data

     list.sortData();//sort the  data

     cout<<"\n--- After sorting the data---\n";

     list.print();//print the data

     cout<<"Enter the element to search\n";

     int x;

     cin>>x;//get element to search

     list.searchElement(x);//call the search function

 }

 catch (std::bad_alloc){

   cout<<"Sorry, could not allocate memory for list object.";

 }

 }else{

   throw('Negative Number detected');

 }

 }

 catch (int n){

   cout<<"The number should be a positive integer.";

 }

   return 0;

}

Explanation:

The try and catch keywords come in pairs, as they are used to control exceptions in the C++ source code. The try keyword checks for error in the source code given the condition (if the n integer variable is greater than 0). If the condition is met, the code in the try code block runs otherwise the catch keyword catches the error of a negative number (if the n variable in less than 0).

Other Questions