2014-04-16 29 views
0

我正在寫這段代碼,並且不斷收到一個運行時錯誤,告訴我需要捕獲IOException。我怎麼做?這是我的代碼:如何捕獲reset()方法的IOException?

System.out.println("\nThese presidents were born before the states were formed:\n"); // DO NOT REMOVE OR MODIFY 
    ArrayList<String> america = new ArrayList<String>(); 
    String l; 
    String line; 
    while((line = infile2.readLine()) != null) 
    { 

     america.add(line); 
    } 
    Collections.sort(america); 
    infile1.reset(); 
    try 
    { 
     while((infile1.ready())) 
     { 
      ArrayList<String> am = new ArrayList<String>(); 
      l= infile1.readLine(); 
      String [] ls = l.split(" "); 
      for(int i=1; i<ls.length;i++) 
      { 
       am.add(ls[i]); 
      } 
      Collections.sort(am); 
      america.removeAll(am); 
     } 
    } 
    catch(IOException ex) 
    { 
     System.out.println("ERROR"); 
    } 

    System.out.println(america); 
+0

通常,向我們展示您正在討論的堆棧跟蹤/錯誤輸出是個好主意。 –

+0

什麼是infile1? –

回答

0

我懷疑你得到的是編譯錯誤,而不是運行時錯誤。

該行while((line = infile2.readLine()) != null)包含一個方法的調用,該方法可能會拋出IOException但您尚未用try-catch將其包裝。

可能存在與infile1.reset()呼叫相同的問題。

原因是在Java中,檢查異常;如果您正在調用的方法聲明throws FooException,則您需要使用try { ... } catch(FooException e) { ... }將調用包裝爲該方法,或者使用throws FooException(或異常層次結構中的任何異常)標記調用方法。

相關問題