Throw exceptions question..

Apr 13, 2011 at 9:10pm
I am dealing with fractions and want to throw an error if they try and divide by zero. Here's what I have tried...
1
2
if(denom == 0)
		throw "Can't divide by 0";


I don't want this to completely end the program though...
Apr 13, 2011 at 9:40pm
did u use try/catch blocks?

this will not end the program and will not divide anything.
if (denom == 0) denom = 1;

Apr 13, 2011 at 9:43pm
Well with that it will use the denominator as 1. I want to try and throw an exception that tells the user they tried to divide by zero.
Apr 13, 2011 at 9:50pm
@kraigballa: you just need to throw from within a try block and catch it at the end of the block. Read this: http://www.cplusplus.com/doc/tutorial/exceptions/

@sasanet: that is a really, really bad idea. 4 / 0 is not 4. It just doesn't make sense and an error should be signaled.
Apr 13, 2011 at 9:51pm
1
2
3
4
5
6
7
8
9
try {
        //some code...
        if (denom == 0) throw "you have tryed dividing by 0 ";  //throwing char*
        //rest of code
}

catch (char* x) {
       cout << x << endl;  //this will show the "throw sting" to user
}

however this will end try block (rase up exception).
and program continues behind catch block!
Last edited on Apr 13, 2011 at 9:52pm
Apr 13, 2011 at 10:09pm
Yea, I decided to go with the try/catch route. Thanks
Topic archived. No new replies allowed.