Advertisement

Divide by zero error handler in C++ ...

Started by February 22, 2002 04:06 PM
9 comments, last by Alphie 22 years, 8 months ago
Can someone please help me with this? I am trying to figure out how to make a divide by zero error handler in C++. A computer program does what you tell it to do, not what you want it to do.
A computer program does what you tell it to do, not what you want it to do.
Integer divide by zero :
Low level : install an interrupt handler for interrupt 5.
See here

If you do a float divide by zero, the math library will return +/- infinity ( or NaN (Not a Number) for 0/0 ). You can test for these values.

Edited by - Fruny on February 22, 2002 7:40:33 PM
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
You could also test to see if the divisor (denominator) is zero, and throw an exception if it is.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
Ok, I took a Java class and I was thinking about throwing an exception, but how do I do that in C++ ?

A computer program does what you tell it to do, not what you want it to do.
A computer program does what you tell it to do, not what you want it to do.
I may be wrong about the syntax, check your manual.

  #include <exception>class Div0Exception : public std::runtime_error {};template<class T>T divide( const T& lhs, const T& rhs ){  if ( rhs == 0 ) throw Div0Exception;  return lhs / rhs;}  


It won''t help you with a/b for basic types though, since you cannot overload their division operator. Anyways, floats don''t care about divide by zero, but for int types you would need the assembly code above, since it is a hardware interrupt (the µP barfs), not a software exception.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
I still don''t understand... This is what I have, and I have to change it so I can give and error message for divide by zero. Right now, the program gets a runtime error if you divide by zero...


#include <iostream.h>

main()
{

double x, y;
double result;
char cmd;

cout << "\nOperators: * , / , + , - \n";
cout << "Enter a number, an operator, and another number.\n";
cout << "Press the spacebar after each entry.\n\n";
cin >> x;
cin >> cmd;
cin >> y;



switch( cmd )
{
case ''*'':
result = x * y;
cout << "\n\n" << x << " * " << y << " = " << result << "\n\n";
break;
case ''/'':
result = x / y;
cout << "\n\n" << x << " / " << y << " = " << result << "\n\n";
break;
case ''+'':
result = x + y;
cout << "\n\n" << x << " + " << y << " = " << result << "\n\n";
break;
case ''-'':
result = x - y;
cout << "\n\n" << x << " - " << y << " = " << result << "\n\n";
break;
default:
cout << "\n\nInvalid equation: Please try again.\n";
break;
}
}


A computer program does what you tell it to do, not what you want it to do.
A computer program does what you tell it to do, not what you want it to do.
Advertisement
Ok, I finally got my divide by zero handler working. But now I have a new problem. I am trying to get the program to loop until Q is pressed. But I get a warning that says ''running is assigned a value that is never used in function main'' And when I press Q the program goes into a never ending loop. Please help.

#include <iostream.h>

enum Boolean { FALSE, TRUE }; //Truth values

main()
{
Boolean running = TRUE;
double x, y;
double result;
char cmd;

do
{
cout << "\nOperators: * , / , + , - \n";
cout << "Enter a number, an operator, and another number.\n";
cout << "Press the spacebar after each entry.\n\n";
cin >> x;
cin >> cmd;
cin >> y;

if (( x == ''q'' ) || ( x == ''Q'' ))
{
cout << "\n\nYou have chosen to quit the program.";
running = FALSE;
return 0;
}

switch( cmd )
{
case ''*'':
result = x * y;
cout << "\n\n" << x << " * " << y << " = " << result << "\n\n";
break;
case ''/'':
if ( y == 0 )
{
cerr << "\n\nDivide by zero error.\n\n";
return 0;
}
result = x / y;
cout << "\n\n" << x << " / " << y << " = " << result << "\n\n";
break;
case ''+'':
result = x + y;
cout << "\n\n" << x << " + " << y << " = " << result << "\n\n";
break;
case ''-'':
result = x - y;
cout << "\n\n" << x << " - " << y << " = " << result << "\n\n";
break;
default:
cout << "\n\nInvalid equation: Please try again.\n";
break;
}
}
while ( running );
}

A computer program does what you tell it to do, not what you want it to do.
A computer program does what you tell it to do, not what you want it to do.
This is a complete conversion of your program to work with exceptions, plus a few other necessary patches.
#include <iostream>  // I/O header. note the lack of a .h extension#include <stdexcept> // exceptions header// these are mandated with the new headers because they''re in the std namespace.using std::cerr;using std::cin;using std::cout;using std::endl;//int main(void){  bool running = true;  // C++ has a built-in boolean type  double x, y, result;  char cmd;//  while(running)  {    // you can concatenate input and output. cin/cout are objects    // and <</>> are    // operators    cout << "\nOperators:  , / , + , - \n"         << "Enter a number, an operator, and another number.\n"         << "Press the spacebar after each entry.\n"         << "Enter ''0 Q'' to quit.\n";    cin >> x >> cmd >> y;//    // execute your logic in a try block to generate exceptions    try    {      // handle all the commands together now      switch(cmd)      {      case ''q'':     // this is called a fall-through case      case ''Q'':        // this is the procedure for both cases        running = false;        break;  //      case ''/'':        if(y <= 0.00000001)  // doubles can be tricky with zero and                             // tests for equality          throw std::runtime_error("Divide by zero");          break;  //      // other cases    }//    // every try needs a catch where the exception is processed    catch(std::runtime_error &e)    {      cerr << e.what() << endl;    }  }  return 0;} 


[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
Thank you for going through the trouble to rework my program, but you are WAY ahead of where I am at.
I have not learned all of that extra stuff you put in there and don''t understand it. I really need to work it out from what I have got so far.
And at school they are using Turbo C++ 4.5, which does not yet have the built in boolean type, and does not like it if you leave the .h off of it.
I also don''t understand why you left the * , -, and + out of the switch statement...
I am really confused here...
Isn''t there a way to make this work with what I have already?

Thanks again

Alphie


A computer program does what you tell it to do, not what you want it to do.
A computer program does what you tell it to do, not what you want it to do.
  typedef int boolconst int true = 1;const int false = 0;  


Now you have a boolean type =)

As for the parts he left out, i think he wanted to leave something for you to do. his code is nothing terribly complicated if you go through it slowly. he commented it well.

This topic is closed to new replies.

Advertisement