2016-11-30 112 views
0

在此示例中從不拋出IO異常。爲什麼在此代碼中永遠不會拋出IOException

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

在下面的程序中,它沒有顯示任何錯誤。 公共靜態無效的主要(字串[] 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

回答

2

無論Scanner sc = new Scanner(System.in);也不r = sc.nextDouble(); 被拋出IOException異常,你爲什麼要沒收?

第二個片段是另一個故事:

這個對象:

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

可以肯定地拋出IOException異常

相關問題