为什么EOFException主要由数据输入流使用? [英] Why is EOFException used mainly by data input streams?

查看:148
本文介绍了为什么EOFException主要由数据输入流使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自Java API

From Java API


公共类 EOFException 扩展IOException

public class EOFException extends IOException

表示在输入期间意外地达到了文件结尾或流结束

Signals that an end of file or end of stream has been reached unexpectedly during input.

这个例外主要用于数据
输入流
来表示流的结束。请注意,许多其他输入
操作在流末尾返回特殊值
而不是
抛出异常。

This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.

那么为什么数据输入流与其他输入操作有如此不同?为什么它不像其他输入操作那样返回特殊值来表示流的结束?因为我认为异常只应用于非常特殊的情况。

So why are data input streams so different from other input operations? Why doesn't it return a special value just like other input operations to signal the end of the stream? Because I think exception should only be used on really exceptional cases.

推荐答案

需要带外返回值才能发出信号EOS。返回基元时使用所有带内值,因此没有可用的带外值,因此它必须是例外。

An out-of-band return value is required to signal EOS. All the in-band values are used when returning primitives, so there are no out-of-band values available, so it has to be an exception.

同样适用于 ObjectInput.readObject() null 是带内值,因此不能用于表示EOS。

Same applies to ObjectInput.readObject(). null is an in-band value, so it can't be used to signal EOS.

这是不同的来自 InputStream.read(),返回-1或字节值-128..127。在这种情况下,-1是带外的。

This is different from InputStream.read(), which returns either -1 or a byte value -128..127. In this case -1 is out of band.

假设 readUTF()抛出 EOFException 用于与其他方法对称,尽管它可能在EOS返回null。

One assumes that readUTF() throws EOFException for symmetry with the other methods, although it could probably have returned null at EOS.

这篇关于为什么EOFException主要由数据输入流使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆