help me find a BUG in a little C++ program
This is my source of program
[root@localhost mycpp]# ls dive.cpp dive.h glibc.c linuxsoc main.cpp try1.cpp try2.cpp [root@localhost mycpp]# cat try1.cpp #include <iostream.h> int main () { char myarray[10]; try { for (int n=0; n<=10; n++) { if (n>9) throw "Out of range"; myarray[n]='z'; } } catch (char * str) { cout << "Exception: " << str << endl; } return 0; } [root@localhost mycpp]# so I compile it [root@localhost mycpp]# make try1 g++ try1.cpp -o try1 In file included from /usr/include/c++/3.2.2/backward/iostream.h:31, from try1.cpp:1: /usr/include/c++/3.2.2/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the <X> header for the <X.h> header for C++ includes, or <sstream> instead of the deprecated header <strstream.h>. To disable this warning use -Wno-deprecated. [root@localhost mycpp]# and run the program so this is my result ------------->> [root@localhost mycpp]# ./try1 Aborted [root@localhost mycpp]# what's up?? I think the output must be "Exception: Out of range" :confused: |
catch (const char *str)
and <iostream.h> changes to <iostream> and using namespace std; to get rid of the warnings. |
the problem is your throwing "Out of range" which is a const char * which is not castable to a char * hence why its not being caught. you can fix this by either catching const char * or by throwing something castable to a char *
|
Or even catch (...)
kev's comment reminds me of a nice article about exception handling and casting, which, although not immediately relevent here might be of interest to anyone reading the thread: http://www.cuj.com/documents/s=7979/...lop/hyslop.htm HTH |
All times are GMT -5. The time now is 10:07 AM. |