在catch块中重新抛出异常 [英] Re-throw an exception inside catch block
本文介绍了在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
这篇关于在catch块中重新抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文