gpt4 book ai didi

C++ Try Catch block 不捕获异常

转载 作者:太空狗 更新时间:2023-10-29 23:28:26 29 4
gpt4 key购买 nike

我是 C++ 的初学者,我正在尝试创建一个简单的控制台程序来计算线性方程的“m”和“b”...为了解析用户提供的 double 输入,我使用的是字符串流和使用 try-catch block 检查错误输入。即使 catch block 有全局异常 [Equation Solver.exe 中 0x74c8b9bc 处未处理的异常:Microsoft C++ 异常:内存位置 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 block 或从 catch block 直接或间接调用的函数中),否则你必须使用 throw 和一个通常是某些异常对象的参数排序。

如果throw在未处理异常时执行std::terminate将被调用以结束您的程序。

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

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

关于C++ Try Catch block 不捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11872349/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com