gpt4 book ai didi

c++ - catch-all 处理程序中的 exception_ptr 在 Centos 7 和 Windows 上运行异常

转载 作者:太空宇宙 更新时间:2023-11-04 12:19:01 24 4
gpt4 key购买 nike

为了避免在编写异常处理代码时堆叠 catch block ,我想尝试使用 c++11 功能编写一个 catch-all 异常处理程序。在这样做的过程中,我注意到一些奇怪的行为在 Centos 7 和 Windows 7 和 8.1 上以相同的方式工作,在两个系统上使用 Code::Blocks IDE(你必须检查设置->编译器->c++11 ISO 复选框以让它工作。)我有两种异常,硬件除以零 (number1/number2) 和合成除以零函数 quotient(number1, number2)当分母为零时抛出一个声明的异常。这是代码:

#include <iostream>
#include <exception>
#include <typeinfo>
#include <stdexcept>

using namespace std;

class DivideByZero : public runtime_error
{
public:
DivideByZero() :
runtime_error("Divide by zero exception") {}
};

template <typename T>
T quotient(T numer, T denom)
{
if (denom == 0)
{
throw DivideByZero();
}
else
{
return numer / denom;
}
}

int main()
{
double number1, number2, ratio;
cout << "Enter a numerator: ";
cin >> number1;
cout << "Enter a denominator: ";
cin >> number2;
try
{
ratio = number1/number2;
//ratio = quotient(number1, number2);
cout << "Result is: " << ratio << endl;
}
catch (...)
{
std::exception_ptr p = std::current_exception();
cerr << "Exception: "
<< (p ?
p.__cxa_exception_type()->name() :
"Anonymous")
<< endl;
}
return 0;
}

我会注释掉硬件或合成除法代码行,然后使用不同的整数和实数类型构建/运行。

对于 i5 和 i7 Intel 处理器,Centos 7 和 Windows 系统的结果相似。

当执行在所有系统上抛出声明的异常的合成除法(商)线时,它对所有整数和实数类型的工作方式相同,正确地将异常编号和声明的异常文本打印到 cerr:

Exception: 12DivideByZero

非常好,没有更多的堆叠异常和遗漏任何可能发生的异常!

然而,当对整数和实数类型执行硬件分界线 (number1/number2) 时,异常处理以不同的方式被完全绕过。对于像 double 这样的真实类型,异常被捕获并且 cerr 文本没有被打印出来,出现的是在导致异常的代码之后打印的显示行,你不应该看到的和看起来是所有真实类型的无限值:

Result is: inf

对于所有整数类型,您甚至都没有得到它,您没有显示行,并且在 Linux 上它正常结束,在 Windows 上它死掉并继续寻找解决您的错误程序的方法。

对我来说似乎很奇怪,我相信一些专家会解释 c++11 中异常处理缺乏一致性。

两个 Windows 系统上的 Code::Blocks 都使用最近下载的 mingw32-g++.exe 进行编译,当然,Centos 7 使用 64 位 g++ 编译器。这并没有什么不同,系统的行为相似。

最佳答案

[expr.mul]/4 The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined...

当为 number2 输入零时,您的程序会出现未定义的行为。这意味着任何结果都是可能的; C++ 标准对此类程序的行为没有任何要求。

关于c++ - catch-all 处理程序中的 exception_ptr 在 Centos 7 和 Windows 上运行异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46563494/

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