作者spider391 (小乖)
看板C_and_CPP
标题[问题] 关於 array out of boundary 的例外处理
时间Fri Apr 17 22:37:00 2009
请问一下
我宣告了一个 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
1F:推 littleshan:用 std::vector 底下的 at() 04/17 22:54
2F:→ littleshan:内建的阵列为了效率,不会帮你做这种检查 04/17 22:54