简体   繁体   中英

Why IOException is never thrown in this code

The IO exception never is thrown in this example.

public static void main(String[] args){
    double r = 0;
    System.out.println("Please enter radius of a circle");
    try{
        Scanner sc = new Scanner(System.in);
         r = sc.nextDouble();
    }catch(NumberFormatException exe){
        System.out.println("Inpvalid radius value");
    }catch(IOException exe){
        System.out.println("IO Error :" + exe);
    }

    double per = 2 * Math.PI *r;
    System.out.println(per);
}

Where as in this below program it is not showing any error. public static void main(String[] args) {

     int radius = 0;
     System.out.println("Please enter radius of a circle");

     try
     {
             //get the radius from console
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             radius = Integer.parseInt(br.readLine());
     }
     //if invalid value was entered
     catch(NumberFormatException ne)
     {
             System.out.println("Invalid radius value" + ne);
             System.exit(0);
     }
     catch(IOException ioe)
     {
             System.out.println("IO Error :" + ioe);
             System.exit(0);
     }
     double perimeter = 2 * Math.PI * radius;

     System.out.println("Perimeter of a circle is " + perimeter);

I don't understand why it is happening. Since both are doing the same purpose Why can't first code throw IOException

Neither Scanner sc = new Scanner(System.in); nor r = sc.nextDouble(); are throwing an IOException , why are you catching that ?

the 2nd snippet is another story:

this object:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

can for sure throw an IOException

IOException just shown if some error from our input. ex, integer type data and we input some String data. this will shown error message.

you can study more in here https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM