Java: what are IOEXceptions in BufferedReader's readLine() for?

后端 未结 6 2170
说谎
说谎 2021-02-06 03:13

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

  1. Why does the part \"in.readLine()\" continuosly ignite IOExceptions? <
6条回答
  •  北海茫月
    2021-02-06 03:58

    BufferedReader.readLine() is declared as potentially throwing an exception, see: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/BufferedReader.html#readLine()

    You either need to catch it, or declare your main method as throwing IOException.

    Ie, either do this:

    try {
        while((s=in.readLine()) != null){
            System.out.println(s);
         }
    } catch(IOException e) {
        // Code to handle the exception.
    }
    

    Or

    public static void main(String[] args) throws IOException { ...
    

提交回复
热议问题