gpt4 book ai didi

c++ - 异常处理 - set_unexpected() 无法调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:55:50 25 4
gpt4 key购买 nike

#include "iostream"
#include "conio.h"
#include "exception"
#include "cstdlib"
using namespace std;

void myunexpected ()
{
cerr << "unexpected called\n";
throw 0; // throws int (in exception-specification)
}

void myfunction () throw (int)
{
throw 'x'; // throws char (not in exception-specification)
}

int main (void)
{
set_unexpected (myunexpected);
try
{
myfunction();
}
catch (int) { cerr << "caught int\n"; }
catch (...) { cerr << "caught other exception (non-compliant compiler?)\n"; }
getch();
return 0;
}

Output(When executed on Visual studio 2008): caught other exception (non-compliant compiler?)

But, I was expecting the output to be:

unexpected called

caught int

NOTE: I executed this program on Visual Studio 2008.

最佳答案

是的,根据标准,输出应该是[#1]:

unexpected called
caught int

gcc 给出 accurate result

请注意,MSVC 在处理异常规范方面是出了名的错误。异常规范被认为是 failed experiment .
AFAIK,MSVC 没有实现异常规范,空的除外 ( throw()/nothrow )

C++03 标准:

[#1] 15.5.2 unexpected()函数 [except.unexpected]

The unexpected() function shall not return, but it can throw (or re-throw) an exception. If it throws a new exception which is allowed by the exception specification which previously was violated, then the search for another handler will continue at the call of the function whose exception specification was violated....

关于c++ - 异常处理 - set_unexpected() 无法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10056909/

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