Ok this time it is simple. Tell me honestly, how many of you when you do a new <object> you always check for bad_alloc exception ?
This is a trick question because having see quite a lot of C++ code here and on Internet, I doubt a lot of existing C++ code do the check. It is almost 100% assumed it will pass. The only exception I saw is code that are low level and program are supposed to run in very small memory footprint environment.
Welcome discussion :)
PS In Java program we don't do the check either. It is same mindset as most C++ developers.
Aha finally someone to share the same thinking as me! Well in another forum poster ne55 was asking why my exception class did not check for bad_alloc exception, what if it fails? He is not wrong but based on practicalities reason most don't. Not to mention if we check every time, we would be peppering our code with bad_alloc exception!
Of cuz in "forever running" program, it is critical as the program does not exit and the likelihood of memory running out is a concern. This is a classic case where we need to check.
Sometimes we should balance practicalities vs technicalities. My personal opinion.
Edit:
Just to add on, dynamic aka heap memory can run out but so does stack memory isn't it? So are we going to catch exception when stack memory runs out?
IMO the point is if you have a "higher level" program running your program you can figure out the error and why it died. If you get an exception like that you are basically already screwed.
Hi firedraco,Catfish maybe my English comprehension is no good but can you all be more direct? Just say like chrisname will or will not code the exception handling for every new <object> :P
Catfish:
Polymorphism and pointers are there for a reason. You can avoid but I believe there will be times when you need to use them isn't it? Suppose you are doing maintenance of legacy C program which uses char * a lot. Or the program uses legacy C API which takes parameter like char * , <object> * then you need to use pointers isn't it ?
As for polymorphism, so far my contact with them is minimal. Guess I am not a very OO guy :)
Exceptions are not error codes. It would be terrible coding practice to surround each new-expression with an individual try-block.
I catch, transfer between threads if necessary, and log the bad_allocs along with all other non-recoverable (under our requirements) exceptions, but it is done with just one handler, not "when you do a new <object>"
@sohguanh no: we use gcc, and its runtime prints out the what() of the uncaught exceptions. I just look at the stderr log file if some non-critical tool terminated unexpectedly.
@Cubbi,
In C#, I usually put a try... catch block in Main(). The catch block just leads to a exception handler. In programs with a GUI, that opens a dialogue which looks like this: http://i.imgur.com/SXpAc.png
(normally the error message will be more helpful than "something bad happened")