我在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