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

后端 未结 6 2182
说谎
说谎 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 04:04

    Using Scanner for reading files (or other type of input) can be extremely inefficient in mid/large scale situations. If you have performance concerns reading thousands or milions of lines, i strongly recommend you use BufferedReader class instead. An example of usage of BufferedReader to read lines from System.in is displayed below:

    public static void main(String[] args) throws Exception {
    
        String line = null;
        BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
    
        try {
            /* This is protected code. If an problem occurs here, catch block is triggered */
            while ( (line = br.readLine()) != null ){
                System.out.println(line); 
            }
        }
        catch (IOException e){
            throw new IOException("Problem reading a line",e);
        }
    }
    

    IOException should be used in try/catch block so can be triggered whenever the protected code inside try suffers of an "exceptional" behavior such as an error. Java has his own Exceptions that are throwned when similar situation happen. For example, ArrayIndexOutOfBoundsException is throwned when you define an array a of size n and you try to access the position a[n+1] somewhere in your code. As ArrayIndexOutOfBoundsException, there are many other Exception classes you can throw and customize with your own messages. The code suitable to an exception should be placed in the protected zone in try block. When the exception occurs in that block, the exception will be handled in catch block with it.

    Look that you don't need to build if/else statements to anticipate the error situation and throw an Exception for each case. You just need to associate possible Exception situations between try and catch block. See more about try/catch blocks is encouraged for safe programming.

提交回复
热议问题