【问题标题】:C++ -- Catching built-in "divide by zero" exception [duplicate]C ++ - 捕获内置的“除以零”异常[重复]
【发布时间】:2014-05-02 00:24:50
【问题描述】:

我正在编写一个前缀计算器程序,由于前缀的结构方式,很难处理除以零。幸运的是,如果 C++ 除以零,它有一个内置异常。我将如何处理以下异常,以便它向控制台返回个性化消息而不是弹出此窗口?当我除以零时,我需要这个窗口不弹出。

template<class T>
T PrefixCalculator<T>::eval(istringstream& input) {  //this function needs to throw an     exception if there's a problem with the expression or operators
char nextChar = input.peek();

//handles when invalid characters are input
if(nextChar > '9' || nextChar == '.' || nextChar == ',' || nextChar < '*' &&      nextChar != 'ÿ') {
    throw "invalidChar";
}

//this while loop skips over the spaces in the expression, if there are any
while(nextChar == ' ') {
    input.get();    //move past this space
    nextChar = input.peek(); //check the next character
}

if(nextChar == '+') {
    input.get();    //moves past the +
    return eval(input) + eval(input);   //recursively calculates the first expression, and adds it to the second expression, returning the result
}

/***** more operators here ******/
if(nextChar == '-') {
    input.get();
    return eval(input) - eval(input);
}

if(nextChar == '*') {
    input.get();
    return eval(input) * eval(input);
}

if(nextChar == '/') {
    input.get();

    return eval(input) / eval(input);
}

/******  BASE CASE HERE *******/
//it's not an operator, and it's not a space, so you must be reading an actual  value (like '3' in "+ 3 6".  Use the >> operator of istringstream to pull in a T value!
input>>nextChar;
T digit = nextChar - '0';

return digit;
//OR...there's bad input, in which case the reading would fail and you should throw an exception
}

template<class T>
void PrefixCalculator<T>::checkException() {
if(numOperator >= numOperand && numOperator != 0 && numOperand != 0) {
    throw "operatorError";
}
if(numOperand > numOperator + 1) {
    throw "operandError";
}
}

【问题讨论】:

标签: c++ windows exception


【解决方案1】:

您用来解释复杂运算的符号不会改变您进行低级运算(例如除法)的方式。在你的代码中的某个地方你必须执行一个简单的x/y,在那个地方,当你知道你要分裂时,检查0

if(y==0)
   // your error handling goes here, maybe simple y=1
stack.pushBack(x/y);

请注意,在 C++ 中,除以 0 并不是真正的例外。引用 Stroustrup - 该语言的创建者:

“低级事件,例如算术溢出和被零除,假定由专用的低级机制而不是异常处理。这使得 C++ 在算术方面能够匹配其他语言的行为. 它还避免了在重流水线架构上发生的问题,例如除以零之类的事件是异步的。”

在你的情况下:

if(nextChar == '/') {
    input.get();
    T x = eval(input);
    T y = eval(input);

    if(!y) handlingTheVeryDifficultSituation();
    return x/y;
}

【讨论】:

  • 代码中没有明确的除以零的位置,因为它是前缀表示法。在运行时,编译器会除以零,然后给出那个错误框。就您而言,我必须处理给定的特定异常,这就是为什么我的问题并不是真正重复的原因。
  • @jordpw 你能提供计算方程的代码(已经存储在 RPN 中)吗?错误检查应该在解析中实现。符号真的无关紧要。
  • ... 然后有人设法将INT_MIN 放入x-1yyou get a DoS issue in win32k.sys (blog.regehr.org/archives/887)
  • 我已在原始问题中添加了相关代码。我将如何自己抛出异常?
  • @jordpw 就在if(nextChar == '/') 下,将eval(input) 都分配给临时变量并检查是否为0?我将编辑我的帖子以显示它,但它有点直截了当......
猜你喜欢
  • 2011-09-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
相关资源
最近更新 更多