I have a java class that holds a Closeable resource internally. This means my class also implements the Closeable interface and closes the internal resource in its own close() method.
What is the expected behavior of my class after it has been closed, and generally any closed object in Java? I see the object in a defunct state, where its internals are closed but clients still have a reference to it. IMO accessing it is a programming error, but bugs happen time to time so the behavior should be reasonable even in this case...
Should I?
What is the canonical Java way?
What is the canonical Java way?
First, let's look at the javadoc of the close()
method:
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
So the answer to your options is "none of the above" for the close()
method. You don't throw an exception, and you don't let exceptions through from the closed resource. If it has been closed, the call must be a NOOP.
Now, let's have a look at some of the Closeable
classes:
Throws
IOException
if an I/O error occurs.
That includes "file closed".
That goes for all the InputStream/OutputStream/Reader/Writer I/O classes.
After a file system is closed then all subsequent access to the file system, either by methods defined by this class or on objects associated with this file system, throw
ClosedFileSystemException
. If the file system is already closed then invoking this method has no effect.
Attempting to invoke any methods except
ioException()
in this formatter after it has been closed will result in aFormatterClosedException
.
URLClassLoader.findClass(name)
Throws
ClassNotFoundException
if the class could not be found, or if the loader is closed.
Conclusion: All the methods (except close()
) throw exceptions, though not IllegalStateException
.
You can of course use IllegalStateException
if you want.