2014-05-02 56 views
-1

我正在寫一個前綴計算器程序,並且由於前綴結構化的方式,很難處理除以零。幸運的是,如果C++除以零,則C++具有內置的異常。我將如何處理以下異常,以便將個性化消息返回給控制檯,而不是彈出此窗口?我需要這個窗口不會彈出,當我分割零。C++ - 捕捉內置的「除零」異常

enter image description here

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"; 
} 
} 
+4

這不是一個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

+0

你在代碼中嘗試了什麼? 'try {} catch(...){}'(no pun intended;)!) –

回答

3

你使用來解釋複雜的運算符號,不會改變你做你的低級別操作的方式 - 像師。某處在你的代碼,你必須執行一個簡單的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; 
} 
+0

代碼中除零之外的地方沒有明確的地方,因爲它是前綴符號。在運行期間,編譯器將被零除,然後給出該錯誤框。就你而言,我必須處理特定的例外,這就是爲什麼我的問題不是真的重複。 – jordpw

+1

@jordpw你能提供用於計算等式的代碼(已存儲在RPN中)?錯誤檢查應該在解析中實現。符號確實沒有關係。 –

+0

...然後有人設法把'INT_MIN'放在'x'和'-1'中''',並且[你在win32k.sys中遇到DoS問題](https://gist.github.com/ taviso/4658638)(http://blog.regehr.org/archives/887) –