I've seen the java doc, and it says that : The number of bytes read, possibly zero, or -1 if the channel has reached end-of-stream
I wonder whether the '-1' means that the connection is closed?
If it is, then why there is an exception named ClosedChannelException
it throws?
What's the difference between these two concepts?
Exceptions are usually used in situations where the usual flow of an application cannot continue and some special handling needs to be applied. Especially exceptions should never be used for control flow handling for events that are expected/usual.
In your situation the JavaDoc clearly states, that -1
is returned if the end of the stream has been reached. For example you read an image file over a stream and all bytes of the image have been read, then -1
is returned to notify your code that no more data is to be expected. This is a usual situation and part of the normal control flow. On the other hand the ClosedChannelException
is thrown, if the channel was locally (i.e. by you) closed and you continue reading. This is unexpected. The data was not fully read and the application cannot continue as usual, as there is - in this example - no image to display.
Another reason - apart from mixing expected and unexpected program flows - for not using Exceptions for control flow in expected situations is performance. In Java Exceptions are a costly thing. An Exception is a pretty large object and collecting the current stacktrace takes some considerable amount of time.
UPDATE 2022-02-14:
Reading data from a remotely closed channel, after the receiving the available data, simply results in 0 bytes read and not in a ClosedChannelException
. I adapted the answer accordingly. Thanks @user207421 for bringing this up.