The java.io.InputStream.close()
method is declared to throw an IOException
. Under what circumstances would such an exception actually be thrown?
Edit: Yes I have read the javadoc. Can anybody be more specific than "when an I/O error occurs"? What I/O error can occur while closing an InputStream
?
The throws keyword in Java is used to declare exceptions that can occur during the execution of a program. For any method that can throw exceptions, it is mandatory to use the throws keyword to list the exceptions that can be thrown.
The Machine class has a public method called run(). This method declares that it throws an IOException. IOException (input-output exception) is part of the Java standard library.
The throws keyword indicates that a certain method can potentially "throw" a certain exception. You need to handle a possible IOException (and possibly other exceptions) either with a try-catch block or by adding throws IOException, (...) to your method declaration.
You should put the code for that in a catch or finally clause for the IOException , even if you would like the exception to propagate upwards. If you use a catch clause and you want to propagate it, you will have to rethrow it.
In the case of input stream reading from a file system, an error can be raised while the file system itself updates the last access time metadata, or some other metadata, on a file during closure. Anyway, this happens almost never in practice.
In the case of an input stream reading from a network connection, an error on closure is a bit more conceivable. A normal closure of a network socket actually involves a closure request (TCP/IP FIN packet) being sent over the connection and waiting for the other end to acknowledge this closure request. (In fact, the other end of the connection then in turn sends a closure request, which the closing end acknowledges.) So in the case of a socket input stream, a closure operation actually involves sending traffic over the connection and the closure can thus fail with an error.
Note that in many implementations, close()
generally doesn't throw an IOException
if the stream is already closed; it simply fails silently to close the stream again.
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