请问有人可以确认这个信息是否正确:
在 C++ 中,在 catch 块内,我们可以使用 throw 语句重新抛出异常,但是所抛出的异常类型应与当前捕获的异常类型相同。
throw;
在 catch 块中单独使用会重新抛出刚刚被捕获的异常。如果需要进行一些清理操作以响应异常,但仍希望将其传播到更全面处理的地方,则此方法很有用:
catch(...)
{
cleanup();
throw;
}
但是你也完全可以这样做:
catch(SomeException e)
{
cleanup();
throw SomeOtherException();
}
事实上,通常方便的做法是这样做,以便将调用代码抛出的异常转换为您记录的任何类型。
重新抛出的异常可能具有不同的类型。 在VS2012上,以下代码可以被正确编译和运行:
#include <iostream>
int main() try
{
try
{
throw 20;
}
catch (int e)
{
std::cout << "An exception occurred. Exception Nr. " << e << std::endl;
throw std::string("abc");
}
}
catch (std::string const & ex)
{
std::cout << "Rethrow different type (string): " << ex << std::endl;
}
输出:
An exception occurred. Exception Nr. 20
Rethrow different type (string): abc
throw;
语句将始终重新抛出已存在的异常,从而带来一些巧妙的技巧。 - Mooing Duck20
没有在你的示例输出中? - Mooing Duck