我在try/catch块中创建了我的类的一个对象,并且想要在异常情况下在catch块中访问它。即使对象创建正常,我也无法在catch块中访问它,因为它在块之外声明。如何在Try中声明变量并在Catch中访问它?
try {
MyObject ob(arg1,arg2); //this can trow exception
ob.func1(); //this also can throw exception
} catch (std::exception& ex){
//I want to access ob here if it was constructed properly and get the reason why func1() failed
}
我可以使用嵌套的try/catch块来解决这个问题,但没有任何其他办法来解决这个
try {
MyObject ob(arg1,arg2); //this can trow exception
try {
ob.func1(); //this also can throw exception
} catch(std::exception& ex) {
//object was constructed ok, so I can access reason/state why the operation failed
}
} catch (std::exception& ex){
//object failed to construct
}
你有一个空的构造函数吗?也许在外面创建默认实例,并在里面设置值,看看它是否会引发异常?但我们能否看到这个构造函数至少有 –
你怎么知道构造不是抛出异常的构造? – juanchopanza
如果它在外部捕获中捕获,则对象构造抛出异常,否则执行将进入内部try/catch – dev