Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is InputStream.close() declared to throw IOException?

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?

like image 884
meriton Avatar asked May 04 '13 00:05

meriton


People also ask

What is the purpose of using throws IOException?

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.

Which method will throw an IOException?

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.

What does throws IOException mean in Java?

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.

How do you handle IOException in Java?

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.


1 Answers

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.

like image 77
Konstantin Yovkov Avatar answered Sep 19 '22 07:09

Konstantin Yovkov