在catch块中重新抛出异常
问题描述:
任何人都可以确认此信息是否正确:
Can anyone please confirm me if this information is correct or not:
在C ++中,在catch块中,我们可以使用throw语句重新抛出异常,抛出的异常应该与当前捕获的异常类型相同。
In C++, inside catch block we can re-throw an exception using throw statement, but the thrown exception should have the same type as the current caught one.
答
rethrown异常可以有不同的类型。
在VS2012上编译并正确运行
The rethrown exception can have a different type. This compiles and runs correctly on VS2012
// exceptions
#include <iostream>
using namespace std;
int main () {
try{
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. " << e << '\n';
throw string("abc");
}
}
catch (string ex)
{
cout<<"Rethrow different type (string): "<< ex<<endl;
}
return 0;
}
输出:
发生异常。异常Nr。 20
An exception occurred. Exception Nr. 20
Rethrow不同类型(字符串):abc
Rethrow different type (string): abc