Java:BufferedReader的readLine()中的IOEXceptions是什么?

hhh*_*hhh 7 java exception ioexception

我可以用try-catch循环"修复"下面的异常,但我无法理解原因.

  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);
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

Yis*_*hai 8

基本思想是BufferedReader委托给不同类型的Reader,因此传递该异常.

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

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