1

Here is my code I am using this code to input number of test cases of a problem in codechef but this error occurs whereas in my local machine ubuntu 20.04LTS it successfully compiles.

import java.io.*;
import java.math.BigDecimal;
import java.util.*;

class WorldRecord {
   

    public static void main(String args[])throws IOException
    {
        //Scanner b=new Scanner(System.in);
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int t;
        try{
        t = Integer.valueOf(br.readLine().trim());
        }
        catch(NumberFormatException e){
            System.err.println(e);
        }
        catch(IOException e){
            System.err.println(e);
        }
        catch(NullPointerException e){
            System.err.println(e);
        }
        finally{
            t = Integer.parseInt(br.readLine().trim());
        }

        
    }
}

Here is my error

java.lang.NullPointerException
Exception in thread "main" java.lang.NullPointerException
    at WorldRecord.main(Main.java:26)

  • 3
    documentation of `readLine()`: *"...`null` if the end of the stream has been reached..."* : always check if the returned value is `null` or not - it's a bit *unconventional* to read input in a `finally` block, eventually after a previous error –  Apr 03 '21 at 07:19
  • 2
    Also you should not catch `NullPointerException` as its runtime exception and indicates programmers mistakes. It should be prevented with `null` checks or proper method use. And don't forget to run `br.close()` in `finally` block, also you should wrap the `System.in` in decorator to prevent it from closing. – Andrei Yusupau Apr 03 '21 at 07:23

0 Answers0