我正在寫一個前綴計算器程序,並且由於前綴結構化的方式,很難處理除以零。幸運的是,如果C++除以零,則C++具有內置的異常。我將如何處理以下異常,以便將個性化消息返回給控制檯,而不是彈出此窗口?我需要這個窗口不會彈出,當我分割零。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]進行處理(http://msdn.microsoft.com/en-我們/庫/窗/臺式機/ ms680657%28V = vs.85%29.aspx)。請參閱http://stackoverflow.com/q/1909967/420683和http://stackoverflow.com/questions/4747934/c-catch-a-divide-by-zero-error – dyp
你在代碼中嘗試了什麼? 'try {} catch(...){}'(no pun intended;)!) –