Jump to content

C++ Exception handling

- - - - -

  • Please log in to reply
2 replies to this topic

#1
SPorg

SPorg

    Newbie

  • Members
  • Pip
  • 2 posts
Hi all,

I am trying to terminate my program when the user is trying to perform a division operation by zero, but what happens is the program doesn't teminate gracefuly. It just say integer division by zero!

leftresult = evaluate (node->left_operand);
rightresult = evaluate(node->right_operand);
if (((rightresult >= 0) && (leftresult > 0)) ||
((rightresult <= 0) && (leftresult < 0))){
try {
result = leftresult / rightresult;
} catch (char * s) {
throw;
cout << s <<endl;
}

else if (((rightresult >= 0) && (leftresult < 0)) ||
((rightresult <= 0) && (leftresult > 0))){
try {
result = ((abs(leftresult) / abs(rightresult)) + 1) * (-1);
}
catch (char *s){
throw;
cout << s <<endl;
}
}

break;

Any help is appreciated.

#2
mebob

mebob

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 490 posts
I think you have to do something like throw "Division by zero!"; or the likes, that's what it says on MSDN.

#3
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
Don't have much experience with exceptions myself, but as mebob said you have to throw something first and then catch it.
try {
    int a = 5;
    int b = 0;
    
    if (b == 0)
        throw "division by zero";
    else
        int c = a / b;
} catch (std::string& s) {
    std::cout << "exception caught: " << s << std::endl;
} catch (...) {
   std::cout << "unhandled exception caught" << std::endl;
}

A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users