2012-08-08 43 views
2

我是C++的初學者,試圖創建一個簡單的控制檯程序來計算線性方程的'm'和'b'...來解析輸入double用戶提供,我正在使用一個stringstream並使用一個try-catch塊來檢查錯誤的輸入。持久性錯誤持續下,即使catch塊有[方程式Solver.exe未處理的異常在0x74c8b9bc:微軟C++異常:[重新拋出]在內存位置00000000 ..]一個全局異常C++ Try Catch Block沒有發現異常

double XOne;`enter code here` 
double YOne; 
double XTwo; 
double YTwo; 
bool inputCheck = false; 
while (inputCheck == false) 
{ 
    Clear(); 
    WriteLine("**Linear Equation**"); 
    Write("X1: "); 
    string xone = ReadLine(); 
    Write("Y1: "); 
    string yone = ReadLine(); 
    Write("X2: "); 
    string xtwo = ReadLine(); 
    Write("Y2: "); 
    string ytwo = ReadLine(); 
    try 
    { 
     stringstream s1(xone); 
     if (s1 >> XOne) { s1 >> XOne; } else { throw; } 
     stringstream s2(yone); // consider I give an invalid input for this variable 
     if (s2 >> YOne) { s2 >> YOne; } else { throw; } // this doesn't solve the problem 
     stringstream s3(xtwo); 
     if (s3 >> XTwo) { s3 >> XTwo; } else { throw; } 
     stringstream s4(ytwo); 
     if (s4 >> YTwo) { s4 >> YTwo; } else { throw; } 
    } 
    catch (...) { WriteLine("Invalid Input"); ReadLine(); } 
} 

LinearEquation equation; 
equation.Initialize(XOne, YOne, XTwo, YTwo); 
stringstream s5; 
s5 << equation.m; 
string m = s5.str(); 
stringstream s6; 
s6 << equation.b; 
string b = s6.str(); 
Write("Y = "); 
Write(m); 
Write("X + "); 
WriteLine(b); 
ReadLine(); 

編輯 第一個建議像魅力一樣工作......謝謝! 這是根據評論者修改後的代碼。

double XOne; 
double YOne; 
double XTwo; 
double YTwo; 
bool inputCheck = false; 
while (inputCheck == false) 
{ 
    Clear(); 
    WriteLine("**Linear Equation**"); 
    Write("X1: "); 
    string xone = ReadLine(); 
    Write("Y1: "); 
    string yone = ReadLine(); 
    Write("X2: "); 
    string xtwo = ReadLine(); 
    Write("Y2: "); 
    string ytwo = ReadLine(); 
    try 
    { 
     stringstream s1(xone); 
     if (s1 >> XOne) { s1 >> XOne; } else { throw runtime_error("Invalid Input"); } 
     stringstream s2(yone); 
     if (s2 >> YOne) { s2 >> YOne; } else { throw runtime_error("Invalid Input"); } 
     stringstream s3(xtwo); 
     if (s3 >> XTwo) { s3 >> XTwo; } else { throw runtime_error("Invalid Input"); } 
     stringstream s4(ytwo); 
     if (s4 >> YTwo) { s4 >> YTwo; } else { throw runtime_error("Invalid Input"); } 
    } 
    catch (runtime_error e) { WriteLine(e.what()); ReadLine(); } 
} 

LinearEquation equation; 
equation.Initialize(XOne, YOne, XTwo, YTwo); 
stringstream s5; 
s5 << equation.m; 
string m = s5.str(); 
stringstream s6; 
s6 << equation.b; 
string b = s6.str(); 
Write("Y = "); 
Write(m); 
Write("X + "); 
WriteLine(b); 
ReadLine(); 

回答

14

throw沒有參數的當存在正在處理的異常只能用(即,在catch塊或直接或間接地從一個catch塊調用的函數),否則必須使用擲與參數這通常是某種異常對象。

如果在未處理異常時執行throw將調用std::terminate來結束程序。

例如(在#include <stdexcept>之後)

throw std::runtime_error("Bad input");