![](/img/trans.png)
[英]Why is there a need for a try block before catch in exception handling c++
[英]C++ Try Catch Block does not catch an exception
我是C ++的初學者,並試圖創建一個簡單的控制台程序來計算線性方程的'm'和'b'...來解析用戶提供的輸入雙,我使用的是字符串流並嘗試使用-catch塊檢查錯誤輸入。 即使catch塊具有全局異常,持久性錯誤也會繼續跟蹤[方程Solver.exe中的0x74c8b9bc處的未處理異常:Microsoft C ++異常:[rethrow]在內存位置0x00000000 ..]
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();
沒有參數的throw
只能在處理異常時使用(即在catch塊或直接或間接從catch塊調用的函數中),否則你必須使用帶有參數的throw,這通常是一個異常對象某種。
如果在未處理異常時執行throw
將調用std::terminate
來結束程序。
例如(在#include <stdexcept>
)
throw std::runtime_error("Bad input");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.