简体   繁体   中英

what's the difference between ClosedChannelException and -1 in Java SocketChannel read function

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 (remotely) closed before all data was read. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM