大家好,我在理解以下处理未捕获异常的代码时遇到了一些困难,并且我对下面的示例有一些疑问。
1)只是想知道为什么输出是:“调用我的意外”和“捕获错误的表达式”而不是“调用我的意外”,“捕获 X”
2) 'void f()' 函数中的 throw(X,Y, bad_exception)
意味着什么。
3) typedef void (*pfv)();
实际上意味着什么
class X { };
class Y { };
class A { };
typedef void (*pfv)();
void my_terminate() {
cout << "Call to my_terminate" << endl;
abort();
}
void my_unexpected() {
cout << "Call to my_unexpected" << endl;
throw;
}
void f() throw(X,Y, bad_exception) {
throw A();
}
void g() throw(X,Y) {
throw A();
}
int main()
{
pfv old_term = set_terminate(my_terminate);
pfv old_unex = set_unexpected(my_unexpected);
try {
cout << "In first try block" << endl;
f();
}
catch(X) {
cout << "Caught X" << endl;
}
catch(Y) {
cout << "Caught Y" << endl;
}
catch (bad_exception& e1) {
cout << "Caught bad_exception" << endl;
}
catch (...) {
cout << "Caught some exception" << endl;
}
}
很抱歉提出了多个问题,希望有人能够用通俗的语言向我解释。谢谢并赞赏..
最佳答案
1) 当您调用 f
时,它会抛出一个异常,该异常的类型 (A
) 不属于其异常规范的一部分。这会导致调用已注册的意外处理程序,在本例中为 my_unexpected
。这会打印“Call to my_unexpected”,然后重新抛出原始异常(如前所述,该异常的类型不属于 f
的异常规范的一部分),这会导致 bad_exception
被抛出(但只是因为 bad_exception
是 f
异常规范的一部分)。然后在 main
中捕获该异常,并打印“Caught bad_exception”。
2) 这意味着“f
可能会抛出 X
、Y
或 bad_exception
,并且如果它尝试抛出任何其他内容,然后将调用意外的处理程序”。
3) 这意味着“pfv 是指向不带参数且返回类型为 void 的函数的指针类型”。因此pfv old_term;
意味着old_term
就是这样一个函数指针。
这是一个有用的链接,就其值(value)而言:
特别相关的部分在底部,它说(强调我的):
If unexpected() did not throw (or rethrow) an object allowed by the exception specification of f(), then the C++ run time does one of two things:
- If the exception specification of f() included the class std::bad_exception, unexpected() will throw an object of type std::bad_exception, and the C++ run time will search for another handler at the call of f().
- If the exception specification of f() did not include the class std::bad_exception, the function terminate() is called.
关于C++ 处理未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20177639/