When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
If your construction fails and throws an exception, ~Mutex() will not be called and mutex_ will not be cleaned up. Don't throw exceptions in constructors.
When an exception is thrown, destructors of the objects (whose scope ends with the try block) are automatically called before the catch block gets executed. That is why the above program prints “Destructing an object of Test” before “Caught 10“.
The short answer to the question “can a constructor throw an exception in Java” is yes! Of course, properly implementing exceptions in your constructors is essential to getting the best results and optimizing your code.
Assume the following code:
Foo* p = new (std::nothrow) Foo();
'p' will equal 0 if we are out of heap memory.
What happens if we are NOT out of memory but Foo's constructor throws? Will that exception be "masked" by the nothrow version of 'new' and 'p' set to 0?... Or will the exception thrown from Foo's constructor make it out of the function?
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