[問題] 關於 array out of boundary 的例外處理
請問一下
我宣告了一個 array,做了 out of boundary 的存取
int num[10];
int* c = new int[10];
c[21] = 0;
我想利用例外處理的方式來自動幫我找出 out of array boundary 的錯誤
於是我寫了下列的 code 作測試
===================================================
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int* c = new int[10];
try{
c[21]=9;
}catch ( out_of_range ex ) {
cerr << ex.what() << endl;
exit( EXIT_FAILURE );
throw;
}catch(...){
cerr << "caught other exception (non-compliant compiler?)\n";
throw;
}
return 0;
}
====================================================
初乎我想像的發現,對於 c[21] = 9 這樣的存取, out_of_range 攔截不到
我 google 了一下
http://www.java2s.com/Tutorial/Cpp/0280__STL-Introduction/0140__out_of_range-ex
是否 out_of_range 只適用於 std 函式庫
若是這樣的話,請問有什麼較好的方法可以利用 exception handling 的方式處理 out
of boundary array
目前我是打算自己寫 throw
eq.
================================================
int* c = new int[10];
try{
int n=21;
if(n<10)
c[n]=9;
else{
throw "out of boundary";
}
}catch(const char* str){
cerr << str << endl;
}
=================================================
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.224.234.239
推
04/17 22:54, , 1F
04/17 22:54, 1F
→
04/17 22:54, , 2F
04/17 22:54, 2F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章