[英]Application crashes when exception is thrown from constructor
從類構造函數引發異常時,程序崩潰。 在調試模式下運行時,出現以下錯誤“ VirtualCtor.exe在0x74A2DB18處出現未處理的異常:Microsoft C ++異常:在內存位置0x00000000 [重新拋出]。” 它也會在發布模式下崩潰。 我明白這是因為throw找不到確切的catch處理程序,並且調用了std :: terminate()。 但是,我的理解是catch(...)應該處理此問題。 有人可以讓我知道需要與catch一起使用的確切處理程序嗎?
#include<iostream>
#include<exception>
using namespace std;
class MyClass
{
public:
MyClass() { cout << "Default Ctor" << endl;
throw; //runtime exception.
}
~MyClass()
{
cout << "Destructor called" << endl;
}
};
int main()
{
MyClass*vpt = nullptr;
try {
vpt = new MyClass;
}
catch (...) {
delete vpt;
cout << "Exception"<< endl;
}
return 0;
}
更改代碼將拋出bad_alloc(); 捕獲異常,代碼不再崩潰,但我需要了解僅從函數/構造函數調用throw會發生什么情況?
謝謝。
您不會拋出異常。 您只是在編寫throw
,它會重新拋出一個已經拋出的異常。 在這種情況下,沒有一個,因此您的程序具有未定義的行為。 因此崩潰。
如果要扔東西,實際上必須扔東西!
MyClass()
{
cout << "Default Ctor" << endl;
throw std::runtime_exception("Testing exception handling");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.