我正在编写一个前缀计算器程序,由于前缀的结构方式,很难处理除以零。幸运的是,如果C ++除以零,它就有一个内置异常。我如何处理以下异常,以便它向控制台返回个性化消息而不是弹出这个窗口?当我被ZERO分开时,我需要这个窗口不会弹出。
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";
}
}
答案 0 :(得分:3)
您用来解释复杂操作的符号,并不会改变您执行低级别操作的方式 - 例如除法。在代码的某处,您必须执行一个简单的x/y
,在那个地方,当您知道自己将要分裂时,请检查0
:
if(y==0)
// your error handling goes here, maybe simple y=1
stack.pushBack(x/y);
请注意,在C ++中,除以0并不是一个例外。引用Stroustrup - 语言的创造者:
&#34;假设低级事件(例如算术溢出和除以零)由专用的低级机制而不是异常处理。这使C ++能够在算术时匹配其他语言的行为。它还避免了在严重流水线架构上出现的问题,其中除以零之类的事件是异步的。&#34;
在你的情况下:
if(nextChar == '/') {
input.get();
T x = eval(input);
T y = eval(input);
if(!y) handlingTheVeryDifficultSituation();
return x/y;
}