2017-04-16 36 views
-3

我寫一個Java文件,但是當我嘗試編譯它,我一直得到3錯誤信息:Java「的嘗試沒有抓」和「抓而不嘗試」

reader.java:35:錯誤:「嘗試「沒有 '抓', '最後' 或資源聲明 嘗試

reader.java:48:錯誤: '抓' 沒有 '嘗試' 趕上(IOException異常E)

reader.java:52:錯誤:'catch'without'try' catch(Exception e)

3錯誤

爲什麼?我錯過了什麼?這裏是我的代碼:

public static void processRecords(String filenameIn, Person[] personArray) 
{ 
    try 
    { 
     FileReader fr = new FileReader(filenameIn); 
     BufferedReader reader = new BufferedReader(fr); 
     reader.readLine(); 

     for (int i = 0; i <personArray.length; i++) 
     { 
      String[] data = reader.readLine().split("/t"); 
      personArray[i] = new Person(Integer.parseInt(data[0]), data[1], data[2], Integer.parseInt(data[3])); 
     } 
    } 
     reader.close(); 
    catch(IOException e) 
    { 
     System.out.println("ERROR: WRONG FILE " + e.toString()); 
    } 
    catch(Exception e) 
    { 
     System.out.println("ERROR" + e.toString()); 
    } 
} 
+0

你'reader.close()'調用是在錯誤的地方! – Li357

+0

欲瞭解更多信息:http://stackoverflow.com/questions/35321312/java-try-catch-block –

+0

try塊必須跟在catch塊之後;之間沒有任何東西所以將reader.close()移入try塊。 – GhostCat

回答

2

你不能把trycatch之間reader.close()。要麼將其放入finally block,要麼使用try-with-resources。像,

try (BufferedReader reader = new BufferedReader(new FileReader(filenameIn))) { 
    reader.readLine(); 
    for (int i = 0; i < personArray.length; i++) { 
     String[] data = reader.readLine().split("/t"); // <-- should be \\t for tab. 
     personArray[i] = new Person(Integer.parseInt(data[0]), data[1], 
       data[2], Integer.parseInt(data[3])); 
    } 
} catch (IOException e) { 
    System.out.println("ERROR: WRONG FILE " + e.toString()); 
} catch (Exception e) { 
    System.out.println("ERROR" + e.toString()); 
} 

或與finally塊,

BufferedReader reader = null; 
try { 
    reader = new BufferedReader(new FileReader(filenameIn)); 
    reader.readLine(); 
    for (int i = 0; i < personArray.length; i++) { 
     String[] data = reader.readLine().split("\\t"); // <-- to split on tab. 
     personArray[i] = new Person(Integer.parseInt(data[0]), 
       data[1], data[2], Integer.parseInt(data[3])); 
    } 
} catch (IOException e) { 
    System.out.println("ERROR: WRONG FILE " + e.toString()); 
} catch (Exception e) { 
    System.out.println("ERROR" + e.toString()); 
} finally { 
    if (reader != null) { 
     reader.close(); 
    } 
} 
0

您也可以消除reader.close()通過使用try-與資源乾脆打電話。

嘗試(FR的FileReader =新的FileReader(filenameIn)){ ... }