2015-10-12 35 views
0

我想知道如何在發生異常後繼續執行代碼。想象一下,我有一個充滿數字的文本文件。我想讓我的程序讀取所有這些數字。現在,假設有一個字母混合在一起,是否有可能捕獲異常,然後代碼繼續循環?我需要嘗試並捕獲一個do-while循環嗎?請給我提供你的想法,我非常感謝。我已經提供了我的代碼以防萬一:爲什麼我的Java程序在捕獲到異常後退出?

NewClass newInput = new NewClass(); 
    infile2 = new File("GironEvent.dat"); 
    try(Scanner fin = new Scanner (infile2)){ 
     /** defines new variable linked to .dat file */ 
     while(fin.hasNext()) 
     { 
      /** inputs first string in line of file to variable inType */ 
      inType2 = fin.next().charAt(0); 
      /** inputs first int in line of file to variable inAmount */ 
      inAmount2 = fin.nextDouble(); 

      /** calls instance method with two parameters */ 
      newInput.donations(inType2, inAmount2); 
      /** count ticket increases */ 
      count+=1; 
     } 
     fin.close(); 
    } 
    catch (IllegalArgumentException ex) { 
       /** prints out error if exception is caught*/ 
       System.out.println("Just caught an illegal argument exception. "); 
       return; 
      } 
    catch (FileNotFoundException e){ 
     /** Outputs error if file cannot be opened. */ 
     System.out.println("Failed to open file " + infile2 ); 
     return; 

    } 
+1

您可以在循環內放置一個try-catch塊,其中catch塊只記錄錯誤並跳轉到下一次迭代循環。 – t0mppa

回答

3

在循環中聲明您的try-catch塊,以便循環可以在異常情況下繼續。

在您的代碼中,Scanner.nextDouble將拋出InputMismatchException,如果下一個標記不能轉換爲有效的double值。那就是你想要在你的循環中捕獲的異常。

0

是的,我會把你的try/catch在你的while循環,但我想你需要刪除return語句。

0

是的。這些傢伙沒錯。如果你把try-catch放在循環中,異常將會保留在循環內部。但是現在你有這種方式,當拋出一個異常時,異常將會「斷開」循環並繼續前進,直到它到達try/catch塊。像這樣:

try     while 
    ^
    | 
    while   vs  try 
    ^     ^
    |      | 
Exception thrown  Exception thrown 

你的情況,你想 try/catch塊:一個用於打開該文件(外循環),另一個用於讀取文件(內循環)。

0

如果你想捕捉異常後繼續:當你遇到異常

  1. 刪除return語句。

  2. 內捕獲並同時由於當前的catch塊環捕獲只有2例外之外的所有可能的例外。查看Scanner API可能出現的異常情況。

  3. 如果你想繼續任何類型的異常後,趕上一個更通用的異常。如果你想在通用異常的情況下退出,你可以通過捕獲返回。

相關問題