I'm getting throw exception and need your review
The main function bellow trying to allocate memory several times and then throw the exception on the upper level.
#include <iostream> #include <memory> struct MiserlinessClass{ char * pMemory; int memory_len; const int max_size = 10; MiserlinessClass(int len){ if (len>max_size){ std::cout<<"What a lavish lifestyle! Get out of my face! \n"; std::bad_alloc exception; throw exception; } pMemory = (char *)malloc(len*sizeof(char)); memory_len = len; } }; int main(int argc, char** argv){ int len = (argc==2)? strtol(argv[1],NULL,10): 5; std::unique_ptr<MiserlinessClass> objPtr; bool allocated = false; const int max_cnt = 5; int cnt = 0; while (!allocated){ try{ std::cout<<"Trying to allocate "<<len<<" chars...\n"; objPtr.reset(new MiserlinessClass(len)); allocated = true; } catch (std::bad_alloc &e){ len = len >> 1; cnt++; if (cnt==max_cnt){ std::cout<<"I give up \n"; throw e; } } } std::cout<< "Allocated " << objPtr->memory_len << " chars \n"; return 0; }
And here are the results of 3 different runs
1 - allocates memory from the very first attempt,
2 - tries few times and allocates available and T
3 - failed after N attempts and throw an exception to the upper level
--------------------------------------- $ make; ./01_exception_pointer 3 make: Nothing to be done for 'all'. Trying to allocate 3 chars... Allocated 3 chars --------------------------------------- $ make; ./01_exception_pointer 64 make: Nothing to be done for 'all'. Trying to allocate 64 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 32 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 16 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 8 chars... Allocated 8 chars --------------------------------------- $ make; ./01_exception_pointer 1023 make: Nothing to be done for 'all'. Trying to allocate 1023 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 511 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 255 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 127 chars... What a lavish lifestyle! Get out of my face! Trying to allocate 63 chars... What a lavish lifestyle! Get out of my face! I give up terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc Aborted (core dumped)
My questions are
I know the formal difference between returning value and throwing the exception, but still can not feel whether it's time to panic and throw an exception or the program should keep calm and just return the error code.
Is is a proper way to handle bad_alloc exception?
Any extra comments and suggestions :)