奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来

Strange message (_Base_bitset::_M_do_to_ulong) getting printed out of overflow exception handler

本文关键字:溢出 异常处理程序 ulong 打印 do 消息 Base bitset to      更新时间:2023-10-16

我正在尝试异常处理,这段代码并没有抛出它想要的字符串:

bitset<134> b;
b.set();
try{
if(!b.to_ulong())
throw std::overflow_error("Overflow occuredn");
}
catch(std::overflow_error& e)
{
cout<<e.what();
}

输出为:

_Base_bitset::_M_do_to_ulong

而当我用这个替换if条件时

if(3>2)

打印预期的字符串。这是怎么回事?

怎么回事:如果位域不适合unsigned longb.to_ulong();会在您有机会之前抛出自己的消息std::overflow_errorif永远不会经过测试。

无论如何,if测试注定要失败。它将对b.to_ulong()返回的任何非零值引发异常。不是你想要的。

我能想到的获取消息的最简单方法是捕获to_ulong抛出的异常并抛出您自己的异常。

#include <iostream>
#include <bitset>
using namespace std;
int main()
{
bitset < 134 > b;
b.set();
try
{
b.to_ulong();
}
catch (std::overflow_error& e)
{
throw std::overflow_error("Overflow occuredn");
}
}

自己执行测试可能比调用to_ulong并处理两个异常更快。

在你的代码中:

bitset<134> b;
b.set();                            // all bits in the set are 1's
try
{
if (!b.to_ulong())              // throws its own std::overflow_error()!
throw std::overflow_error("Overflow occuredn");  // doesn't reach.
}
catch(std::overflow_error& e)
{
cout << e.what();               // catches the exception thrown by b.to_ulong()
}