2012-02-04 127 views
2
public class Employee { 


public static void main(String[] args) { 
    int j=3; 
    staples[] stemp = new staples[j]; 
    String file_name = "d:/personal/11636470/NetBeansProjects/Employee/src/employee/Xanadu.txt"; 

    throws IOException 

    { 

    Scanner s = null; 
    try { 
     s = new Scanner(
        new BufferedReader(
        new FileReader("file_name"))); 

     while (s.hasNext()) 
     { 
      System.out.println(s.next()); 
     } 
     } finally 
     { 
     if (s != null) 
      { 
      s.close(); 
      } 
     } 



try 

{ 

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

for (j=0;j<3;j++) 
     { 
      stemp[j] = new staples(); 

      System.out.print("Enter your name : "); 
      stemp[j].setName(reader.readLine()); 

      System.out.println("Enter your age : "); 
      stemp[j].setAge(Integer.parseInt(reader.readLine())); 


     } 


for (j=0;j<3;j++) 
     { 
      System.out.println("Employee number:" + j +" name:"+stemp[j].getName()+" Age:"+stemp[j].getAge()); 

     } 


reader.close(); // VERY IMPORTANT TO CLOSE 






System.out.println("Program ended"); 

} 

catch(java.io.IOException ex) 
{ 
    System.out.println("Error is " + ex.getMessage()); 
} 



} 

} }Java異常處理查詢

這個問題似乎很簡單,我得到在「拋出IOException異常」路線錯誤,是有什麼錯的try和catch方法,我實現?

該代碼有兩個部分,一個是讀取文件xanadu.txt,另一個是複製獲取員工數據。兩者都嘗試並捕獲實現。

+2

有點重新格式化可能會有所幫助,我感到困惑的是第10行 – DaveRlz 2012-02-04 18:22:00

+0

是的,代碼縮進遍佈整個地方。 – 2012-02-04 18:22:56

+0

讓我重新格式化它 – 2012-02-04 18:23:33

回答

1

這是你完全錯誤的部分。

try 
{ 
    s = new Scanner((Readable) new BufferedReader(new FileReader("file_name"))); 
    while (s.hasNext()) 
     System.out.println(s.next()); 
    } catch (IOException e) 
    { 
     // Do the error stuff. 
     e.printStackTrace(); 
    } finally 
    { 
     // Do it anyway. If error happens or not. 
     if (s != null) 
     s.close(); 
    } 
} 

throws IOException被放置在錯誤的地方,它應該放在這裏:

public static void main(String[] args) throws IOException {

在這種情況下,你不需要任何嘗試,catch塊 - 你只不過是例外,傳遞給覆蓋方法(在你的情況下你不需要擔心它)讓它處理拋出的異常,但是如果你想用try來處理異常,catch塊你不需要這樣。

1

throws子句在方法聲明中有效,不在方法體內。

+0

所以你說拋出IOException應該放在其他地方? – 2012-02-04 18:27:36

+0

是的,它應該是'public static void main(String [] args)拋出IOException {'。主要方法可以聲明爲拋出異常。 – 2012-02-04 18:29:05

+0

或者您可以像Marcin所描述的那樣在您的第一個嘗試塊中捕獲該異常。 – 2012-02-04 18:31:19