0
使用VS2013,在下面的C++代碼中,當訪問具有超出範圍索引的向量時,會得到一個調試斷言,這是正常的(但未達到catch塊)。運行發行版時,程序運行時不會捕獲異常。輸出是1,而它應該是0Visual Studio C++異常未捕獲
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
vector<int> Vector;
void GetException()
try{
int Sum{ 0 };
// Access an element beyond the end of the vector
for(int i = 0; i <= Vector.size(); i++)
Sum += Vector[i];
}
catch(...){
Vector.clear();
}
int _tmain(int argc, _TCHAR* argv[])
{
Vector.push_back(1);
GetException();
cout << Vector.size() << endl;
return 0;
}
當我改變它訪問nullptr我在調試版本得到一個「未處理的異常」,並在發行版本的錯誤消息,崩潰的訪問。 VS中是否有修改異常行爲的參數?
int Sum{ 0 };
void GetException()
try{
int *pSum{ nullptr };
Sum = *pSum;
}
catch(...){
Sum = 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
GetException();
cout << Sum << endl;
return 0;
}
您從迭代器調試功能獲得此診斷。它沒有使用例外來告訴你,你做錯了,捕捉到一個例外從來沒有修復過一個錯誤。你必須修改你的代碼。 –
轉到http://en.cppreference.com/w/cpp/container/vector並閱讀運算符[],然後在()處閱讀。如果你想在元素索引超出範圍時拋出異常,你會發現你想在()使用。 – stijn
@Hans:當然,錯誤必須修復,但捕獲異常允許向用戶顯示一條體面的錯誤消息,以幫助開發人員找到錯誤,然後用戶可以繼續工作(大部分情況是這樣)。程序崩潰可以幫助任何人... –