使用Throw和Catch的未处理异常运行时错误
Unhandled exception runtime error using Throw and Catch
所以我想我理解Throw and Catch,但我不确定。我用它来捕捉除零错误,并在网上看了其他例子,但每次我尝试我的抛出一个未处理的异常错误。我根据赋值的要求在构造函数中使用throw函数,然后尝试在int main中捕获它。有人知道为什么我得到这个运行时错误关于未处理的异常吗?构造函数
Rational(int n, int d)
{
num = n;
denom = d;
normalize();
if (d == 0) {
throw "Divide by Zero";
}
}
Int Main() code
int main()
{
int case_count, a, b, c, d;
cin >> case_count;
for (int i = 0; i < case_count; ++i) {
cout << "Case " << i << "n";
cin >> a;
cin >> b;
cin >> c;
cin >> d;
Rational frac1(a, b);
Rational frac2(c, d);
Rational add;
Rational sub;
Rational mult;
Rational div;
try {
add = frac1 + frac2;
sub = frac1 - frac2;
mult = frac1 * frac2;
div = frac1 / frac2;
}
catch (const char* msg) {
cout << msg;
}
cout << add << " ";
cout << sub << " ";
cout << mult << " ";
cout << div << " ";
cout << (frac1 < frac2) << "n";
cout << frac1.toDecimal() << " ";
cout << frac2.toDecimal() << "n";
}
return 0;
}
Rational
构造函数抛出异常,因此,必须在try
语句中创建Rational对象。在此语句之外创建了许多对象,因此此处抛出的任何异常都是未处理的。
您需要在try语句中创建对象。此外,正如OP中所述,您需要以更好的方式处理异常:
Rational::Rational(int n, int d)
{
num = n;
denom = d;
normalize();
if (d == 0) {
throw std::overflow_error("Divide by zero exception");
}
}
然后做:
try {
Rational frac1(a, b);
Rational frac2(c, d);
Rational add;
Rational sub;
Rational mult;
Rational div;
add = frac1 + frac2;
sub = frac1 - frac2;
mult = frac1 * frac2;
div = frac1 / frac2;
}
catch (std::overflow_error e) {
cout << e.what();
}
在构造函数中抛出异常,特别是接受两个int
s的异常。因此,您必须将该代码放在try块中。
。
try {
Rational frac1(a, b);
}
catch (const char* msg) {
cout << msg;
}
相关文章:
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- VisualC++ 2010 有没有办法找出有关未处理异常错误的更多详细信息
- C++ 程序中双链表的未处理异常
- 运算符重载时未处理<<异常
- 实验室中0x6BE20E11 (ucrtbased.dll) 的未处理异常.exe: 0xC0000005:访问冲突读取
- ImageMagick 的未处理异常
- 类数组大小为的未处理异常
- 尝试将构造函数设置为 0 - c++ 的未处理异常
- Dijkstra 中0x001e1078 s_Algorithm.exe的未处理异常:0xC0000005:访问冲突读取位置0xbaadf00d
- 运算符重载未处理异常
- 尝试使用 fread 读取文本文件时发生 'System.AccessViolationException' 类型的未处理异常
- c++中的Guard,在main中未处理异常时不调用析构函数
- 某些内存位置的未处理异常
- 错误 linkedlist .exe 中0x00D0345E处的未处理异常: 0xC0000005:访问违规写入位置0x
- 仅在发布模式下使用 glGenBuffer 的未处理异常 - QT
- 如何分析VS2010在调试模式下捕获的未处理异常
- glDrawArrays上的openGL未处理异常(GL_TRIANGLES,0,model.indicesCount)
- 使用Boost Spirit解析语法的未处理异常
- 解析"%Z" C++ 中将错误作为访问 voilation 的未处理异常给出?
- 为什么在win32计时器回调中引发的未处理异常未被调试器视为未处理异常