Re: Throwing Constructor Exceptions and cleaning up
Richard Maher wrote ...
If when an object's constructor throws an exception that object has
fact been intantiated, then what happens to the bits/objects/variables
were initialized/instantiated before the exception was thrown?
For example, if I open a file, or connect a socket while constructing an
You would basically do this specifically to adhere to the "resource
acquisition is initialization" (RAII) idiom.
I prefer personally to think of this as "destruction is resource release", but
the point is to tie the resource to the lifetime of the object itself.
However, one does not always follow this pattern; sometimes one prefers to
construct the object first, and acquire or release resources only from
object and then throw an exception before the constructor/instantiation
completes, then what happens to the file or socket connections that were
d) Make sure you close the file/Socket before throwing the exception
Karl Uppiano wrote:
Absolutely. In some cases, the APIs that the constructor needs to call
will themselves throw exceptions. The constructor needs to catch,
cleanup any resources acquired earlier. If you decide to throw a new
exception or otherwise allow one to fly from inside the constructor, you
first need to undo what you have done so far. A well-placed "finally"
block can be very effective in cases where you just want to "let fly"
with an exception thrown by some API that you're using.
The key is that the 'finally' be well placed.
This consideration does sometimes lead to putting resource management in
methods on fully-constructed objects, especially given the lack of explicit
destructors in Java. It depends on the resource, too. A socket may be better
handled in a constructor (perhaps with a last-ditch cleanup in 'finalize' as
discussed elsewhere in this thread). A GUI should not be started in the
constructor, although it should be constructed in the constructor.
The choices hinge on how one ties lifetimes together - the lifetime of the
object and the lifetime of the resource.