【问题标题】:Why IOException is never thrown in this code为什么在这段代码中永远不会抛出 IOException
【发布时间】:2016-11-30 05:40:31
【问题描述】:

本例中从不抛出 IO 异常。

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

在下面的程序中,它没有显示任何错误。 公共静态 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);

我不明白为什么会这样。既然都做同一个目的为什么不能先代码抛出IOException

【问题讨论】:

    标签: java exception-handling ioexception


    【解决方案1】:

    Scanner sc = new Scanner(System.in);r = sc.nextDouble(); 都不是 正在抛出 IOException,你为什么要抓住它?

    第二个sn-p是另一个故事:

    这个对象:

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

    肯定会抛出 IOException

    【讨论】:

      【解决方案2】:

      IOException 只是在我们的输入出现错误时显示。例如,整数类型数据,我们输入一些字符串数据。这将显示错误消息。

      你可以在这里学习更多https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多