How to Catch a string error

  • Thread starter Thread starter StudiousStudent
  • Start date Start date
S

StudiousStudent

Guest
I was hoping somebody could help me with this exercise. All help is much obliged.


Exercise 3: error checking using a string

Write a program that asks the user to enter two integers. Output the result of dividing the first number by the second.

Obviously this will produce an error if the second number is a zero. Surround your calculation with a try block. Check to see whether the second number is a zero and, if it is, throw a string exception with an appropriate error message. Catch the exception using a catch block. Remember that the catch must receive a string parameter if that is what is being thrown. Output the error message inside the catch block.



I can do it with an int exception but not a string.

try
{
int num1, num2;

cout << "First number: ";
cin >> num1;

cout << "Second number: ";
cin >> num2;

if (num2 == 0) throw 0;

cout << num1 / num2 << endl;
}
catch (int x)
{
cout << "Second number is a zero" << endl;
}




StudiousStudent

Continue reading...
 
Back
Top