Problem with exceptions

Hi guys.

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.

Thanks

Here is the code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// prograam to divde two numbers, and return an error if second number is  0
#include <iostream>
#include <string>
using namespace 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 )
{
throw new 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;

}

Throw by value, catch by reference.

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;
}


Thank you so much PanGalactic :)
Ah damn, it is still crashing even the implementations you suggested PanGalactic.
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
anilpanicker,

I tried exiting and also asking the user to enter the number again; but still the program crashes when I input 0 as the divide.

"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;
}
Yay! It works, thank you Chewbob, and thank you other guys for your help :)
I missed that !
Topic archived. No new replies allowed.