正在重试异常
Rethrowing exceptions
为什么以下不处理重新抛出的异常?我尝试了所有的组合,但没有一个能在最后一次接球时显示输出,所以我很困惑!
Derived D;
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
Derived D;
try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}
Derived D;
try {
throw D;
} catch ( const Derived d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
Derived D;
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base b) {
cout << "caught!" << endl;
}
重抛出不是由同一个try-catch
块处理的。它被抛出到调用范围。
在[except.throw]
(2003年措辞)中:
没有操作数的抛出表达式会重新引发正在处理的异常。
和:
当抛出异常时,控制权将转移到具有匹配类型的最近处理程序(15.3);"最近的"表示复合语句、ctor初始值设定项或函数体后面的处理程序try关键字最近由控件的线程输入,尚未退出。
您的try
块已退出,因此其处理程序不是候选程序。因此,代码中的catch
块都不能处理重新抛出。
诚然,这是相当令人困惑的措辞。
try..catch
块捕获,而不是由同一try
块的捕获处理程序捕获。参见此示例:
using namespace std;
class Base
{
public:
virtual ~Base(){}
};
class Derived : public Base
{
};
void f()
{
try
{
throw Derived();
}
catch(Derived& ex)
{
cout<<"Caught in fn";
throw;
}
}
int main()
{
try
{
f();
}
catch(Base& b)
{
cout<<"Caught in mainn";
}
return 0;
}
输出为:
在中捕获
在主中捕获
这应该有效:
Derived D;
try{
try {
throw D;
} catch ( const Derived &d) {
throw;
} catch (const Base &b) {
cout << "caught!" << endl;
}
} catch (const Base &b) {
cout << "caught here!" << endl;
}
正如其他人所说,rethrow
将从catch块中重新抛出相同的异常。
相关文章:
- 尝试将 std::cerr 重定向到文件时出现访问冲突异常
- C++程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出适当的值
- C++设置"blank"或重置 ifstrean (ios) 的异常掩码
- C libcurl错误重试
- 为什么当循环再次运行时,此输出"请重试"?
- CloseHandle 在 STDOUT 重定向后在 Studio 2010 中引发异常
- 网络tcp套接字应用程序重试方法
- 正在重试包含同一异常的exception_ptr的多个实例
- 未收到确认时如何执行数据包重试
- 出现异常后重试本地静态变量初始化
- LIBMEMCACHED :服务器已失败并禁用,直到定时重试
- std::istream 运算符异常重置/未抛出
- Android 冻结在 OpenGL|ES 中(CPU 可能被固定,重试)
- C++异常值重置
- 从catch块中的函数重试
- 在Poco 1.5.x中使用锁定的SQLite数据库重试
- 如何在c++中使用JNI将异常堆栈跟踪重定向到日志文件
- CURL请求失败重试方法
- "相机正在使用中。关闭使用它的所有应用程序,然后重试。在黑莓 Z10 中调用黑莓 10 级联中的相机时
- 正在重试异常