92.7k views
0 votes
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)

User Rstudent
by
7.9k points

1 Answer

3 votes

Answer:

int main()

{

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

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<<"\\--- After sorting the data---\\";

list.print();//print the data

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

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;

}

Step-by-step 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).

User Pavel Shishmarev
by
7.6k points

No related questions found