【发布时间】: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++ 异常 IIRC,而是可以通过 SEH 处理的“硬件异常”。见stackoverflow.com/q/1909967/420683 和stackoverflow.com/questions/4747934/…
-
你在代码中尝试了什么?
try{} catch(...){}(没有双关语;)!)