How handle Errors in Constructor?

Started by
40 comments, last by AndreTheGiant 20 years, 3 months ago
errm, thats a negative.
The memory could fail to allocate for a number of reasons, it might not be the applications fault as such.
Plus, its always better to control your errors, output sane infomation and recover gracefully, unless you enjoy annoying people with your program crashing
Advertisement
quote:Original post by _the_phantom_
errm, thats a negative.
The memory could fail to allocate for a number of reasons, it might not be the applications fault as such.
Plus, its always better to control your errors, output sane infomation and recover gracefully, unless you enjoy annoying people with your program crashing


Yes, that''s true. But still, if a memory allocation fails due to one reason or another chances are very small that you will be able to repair it. Also, all memory is released upon program termination, which means that you can output your message and no memory gets leaked since there is no program that the leak can occur in.

Another nice design I have used is the following. I have a class called init_exception_ex which apart from a std::string also has a _t * (_t being a generic type). Now the user catches init_exception types which have a virtual method cleanup(). This virtual method is overloaded in the generic template classes and clean up the memory leaks. That''s why you can do a nested try/catch in your compiler and do the following

A::A(){try{SomeClass *sc = new SomeClass();}catch(std::bad_alloc){    throw(init_exception_ex<SomeClass>("Error in A::A()", sc);}}


I have no idea if the above code will compile though, I''ve had too little sleep as it is now. So I might have done some stupid error, but I bet y''all know what I mean anyway, heh.
-----------------------------Final Frontier Trader

This topic is closed to new replies.

Advertisement