I am trying to make a simple program to divide two in putted numbers, to try and learn how exceptions work. The exception is supposed to occur if the second input ( the number to be divided by) is 0; the exception should make a string output to the screen. However at the moment if I put in 0 as the second digit the program just crashes. The program works as I want to with valid input.
I'm sure its probably a simple issue; however if you could take a look at my code and offer advice I would appreciate it greatly.
// prograam to divde two numbers, and return an error if second number is 0
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
int x;
int y;
int z;
try
{
cout << " Please enter two numbers " << endl;
cin >> x >> y;
z = x/y;
if ( y == 0 )
{
thrownew string("Its the end of the world");
}
}
catch (string*){;
cout << " nooo" << string("Its the end of the world") << endl;
}
if ( y != 0 )
{
cout << " The result is " << z << endl;
}
system ("pause");
return 0;
}
And I have found that it is always best to either use and existing exception or subclass a standard exception (either std::runtime_error, std::logic_error, or std::exception if neither of those will do).
In your case you can do:
1 2 3 4 5 6 7 8 9
if ( y == 0 )
{
throw string("Its the end of the world");
}
...
catch (string& ex)
{
cout << " nooo" << ex << endl;
}
But I would write:
1 2 3 4 5 6 7 8 9 10 11
#include <stdexcept>
...
if ( y == 0 )
{
throw std::domain_error("Its the end of the world");
}
...
catch (std::domain_error& ex)
{
cout << " nooo" << ex.what() << endl;
}
You got the exception in the catch block, so what do you want to do next.
You need to write the code for the remedy.
you can exit here or you can ask the user to input again or whatever you like
"z = x / y" needs to be after you check if it's 0. Even with the exception stuff, you're still dividing by 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
try
{
cout << " Please enter two numbers " << endl;
cin >> x >> y;
if ( y == 0 )
{
throw domain_error("Its the end of the world")
}
else z = x / y;
}
catch (domain_error &ex)
{
cout << " nooo" << ex.what() << endl;
}