Java: what are ioexceptions in BufferedReader’s readline()?

I can "fix" the following exception with a try catch loop, but I can't understand the reason

>Why does the "in. Readline()" section continuously light ioexceptions? > What is the purpose of throwing such an exception, and the goal may not be just more side effects?

Code and 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);
  }
 }
}

Solution

The basic idea is that BufferedReader delegates to different types of readers, so pass the exception

That different type of reader can read from some volatile external resource, such as the file system in FileReader File system reads can fail at any time for a variety of reasons (the situation will be worse if the reader obtains its basic data from the network stream) The file may be deleted below you (depending on the file system and operating system involved)

Because you can't predict what will happen to the code, you will receive a check exception - the key is that the API tells you that even if there is no problem with the code, you should consider the problem that this operation may not solve

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>