C++ 正在从溢出异常处理程序打印奇怪消息(_Base_bitset::_M_do_to_ulong)

C++ 正在从溢出异常处理程序打印奇怪消息(_Base_bitset::_M_do_to_ulong),c++,exception,C++,Exception,我正在尝试异常处理&这段代码并没有抛出它想要的字符串: bitset<134> b; b.set(); try{ if(!b.to_ulong()) throw std::overflow_error("Overflow occured\n"); } catch(std::overflow_err

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

           bitset<134> b;
           b.set();
           try{
                    if(!b.to_ulong())
                    throw std::overflow_error("Overflow occured\n");
           }
           catch(std::overflow_error& e)
           {
                    cout<<e.what();
           }
将打印所需的字符串。这是怎么回事?

在您的代码中:

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 occured\n");  // doesn't reach.
}
catch(std::overflow_error& e)
{
    cout << e.what();               // catches the exception thrown by b.to_ulong()
}
位集b;
b、 set();//集合中的所有位都是1
尝试
{
如果(!b.to_ulong())//抛出自己的std::overflow_error()!
throw std::overflow_错误(“发生溢出\n”);//未到达。
}
捕获(标准::溢出错误&e)
{

cout发生了什么:
b.to_ulong()
在您有机会之前,如果位字段不能放入
无符号长字符中,则抛出
std::overflow\u错误及其自身的消息。如果
未经测试,则不会测试
if

无论如何,
if
测试都将失败。它将对
b.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 occured\n");
    }
}
#包括
#包括
使用名称空间std;
int main()
{
位集<134>b;
b、 set();
尝试
{
b、 to_ulong();
}
捕获(标准::溢出错误&e)
{
抛出std::溢出\u错误(“发生溢出\n”);
}
}

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

@user4581301在这种情况下,如何打印想要打印的错误消息?
#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 occured\n");
    }
}