,In C# and C++ , no one uses exception handling for new
operator ,what's the reason ?
Is it guaranteed that the call will always be successful ?
Is it guaranteed that the call will always be successful ?
No, this is not guaranteed.
That being said, in general, it's only a good idea to handle exceptions that you can actually do something about. By convention, it's a good idea to design your object construction in such a way to minimize exceptions. That being said, this is not always possible, and many cases, calling new Foo()
can easily throw an exception you may want to catch.
For example, if you try to do this, you're guaranteed to raise an exception, as this is longer than the maximum number of items allowed in an array in a single dimension (even with gcAllowVeryLargeObjects
set):
var willCauseException = new double[int.MaxValue];
Well, no one is a strong expression. In fact, industrial-level applications should check for these errors. But this does not mean that errors should be checked everywhere.
Attempting to create an object with new
can raise an std::bad_alloc
or an OutOfMemoryException
(depending on your language), in addition to any memory that the constructor itself might raise. But if you caught this exception, what would you do with it? The right thing to do is to catch these exceptions in a centralised place (probably at the main loop of the application) and deal with them there. Every time you see one of those messages saying "You are running out of memory: save your current job and exit the application", or the like, it means that one of these exceptions has been caught and dealt with (usually by releasing an emergency memory block to allow for graceful termination and then warning the user).
Exception management does not consist on writing try-catch
blocks everywhere; they must exist only in the right places, and the rest of the code must be written taking into account that exceptions may happen and the system state must be left always in a recoverable state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With