By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,471 Members | 711 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,471 IT Pros & Developers. It's quick & easy.

Add an exception about bad_alloc in a vector of vectors

P: 1
I have a .csv file that i have to read and create a matrix through vector of vectors.
I have a problem about adding a try,catch if the matrix is too big to be stored in memory.
I tried to insert try,catch in different part of the program but noone worked.

Expand|Select|Wrap|Line Numbers
  1.  try {
  2. stringstream convertor(line);
  3. colonne=0;
  4. while (getline(convertor, token,','))
  5. {
  6.    tmp.push_back(stoi(token));
  7.    if (token=="0"){
  8.       zero.push_back(make_triplet(righe,colonne,0));
  9.       contzero++;
  10.                }
  11.       colonne++;
  12. }
  13.   matrix.push_back((tmp));
  14. }
  15.   catch (std::exception& ba)
  16. {
  17. cerr << "bad_alloc caught: " << ba.what() << '\n';
Dec 21 '15 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
This code:

Expand|Select|Wrap|Line Numbers
  1. catch (std::exception& ba)
  2. {
  3.     cerr << "bad_alloc caught: " << ba.what() << '\n';
  4. }
  5.  
is catching a bad_alloc but it is also catching any exception thrown by any object in the try block.

Not good.

You need to try just the push_back of the matrix.

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.    matrix.push_back((tmp));
  4. }
  5. catch (std::bad_alloc& ba)
  6. {
  7.       ... bad_alloc caught here
  8. }
  9. catch (...)
  10. {
  11.      ..all other exceptions caught here
  12. }
  13.  
That said, catching a bad_alloc is pointless because by the time this gets thrown there is no free memory. If you are on Windows you wuld have been getting "windows running low on resources" message boxes for several minutes plus the entire computer will be processing vvvvvveeeeerrrrrryyyyy ssssslllllloooooowwwwwllllyyyyyyy.....
Dec 21 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.