Java:BufferedReader的readLine()中的IOEXceptions是什么? [英] Java: what are IOEXceptions in BufferedReader's readLine() for?

查看:160
本文介绍了Java:BufferedReader的readLine()中的IOEXceptions是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过try-catch循环修复下面的异常,但我无法理解原因。

I can "fix" the below exception with a try-catch loop but I cannot understand the reason.


  1. 为什么in.readLine()部分会连续点燃IOExceptions?

  2. 抛出此类异常的目的是什么,目标可能不只是更多的副作用?

代码和IOExceptions

$ javac ReadLineTest.java 
ReadLineTest.java:9: unreported exception java.io.IOException; must be caught or declared to be thrown
  while((s=in.readLine())!=null){
                      ^
1 error
$ cat ReadLineTest.java 
import java.io.*;
import java.util.*;

public class ReadLineTest {
 public static void main(String[] args) {
  String s;
  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  // WHY IOException here?
  while((s=in.readLine())!=null){
   System.out.println(s);
  }
 }
}


推荐答案

基本思想是BufferedReader委托给另一种类型的Reader,因此传递了该异常。

The basic idea is that a BufferedReader delegates to a different kind of Reader, so it is passing on that exception.

不同类型的Reader可以从中读取某种易失性外部资源,比如FileReader中的文件系统。文件系统读取可能由于多种原因而在任何时候失败。 (如果Reader从网络流获取其基础数据,情况会更糟)。该文件可能会被删除(取决于所涉及的文件系统和操作系统)。

That different kind of Reader can read from some kind of volatile external resource, say a file system in the case of FileReader. A file system read can fail for many reasons at any time. (The situation is worse if the Reader is getting its underlying data from a Network Stream). The file could get deleted out from under you (depending on the file system and OS involved).

因为无法预测代码会发生什么,所以会得到一个检查过的异常 - 关键是API告诉你,即使你的代码没有任何问题,你也应该考虑这个操作可能无法解决的事实。

Because you cannot predict what will happen with code, you get a checked exception - the point being that the API is telling you that you should think about the fact that this operation may not work out even if there is nothing wrong with your code.

这篇关于Java:BufferedReader的readLine()中的IOEXceptions是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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