2017-10-11 178 views
-1

我將字符串轉換爲Integer,所以當我收到任何字符時,拋出異常並且執行停止。我想跳過那個字符並打印所有剩下的數字,所以我一直在while循環中捕獲。但是現在,對於每一個異常,都會拋出一個錯誤,其餘的數字按照異常打印出來,但是一旦拋出異常,代碼必須發送郵件給團隊(我將把郵件部分放入catch中)。如果代碼在每次拋出異常時發送郵件都不好,所以我必須收集while循環內的所有異常並一次性發送有關所有異常的郵件。可能嗎?捕獲while while循環

我將放置簡單的示例代碼。 (郵寄一部分,我稍後會處理爲請告訴我收集所有的異常,並打印一次的邏輯。)

import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 

public class dummy { 
    public static void main(String args[]) { 
     String getEach=""; 
     List A = new ArrayList(); 
     A.add("1"); 
     A.add("2"); 
     A.add("3"); 
     A.add("AA"); 
     A.add("4"); 
     A.add("5"); 
     A.add("dsfgfdsgfdshg"); 
     A.add("30"); 
     Iterator<String> map = A.iterator(); 

     while (map.hasNext()) { 
      try { 
       getEach = map.next(); 
       int getValue = Integer.parseInt(getEach); 
       System.out.println("Value:::::: "+getValue); 
      } catch (Exception E) { 
       System.out.println("There is an exception c" +E.getMessage()); 
      } 
     } 
    } 
} 
+2

使用'List',每增加一個例外(或按摩)的微博,在循環後發送一個郵件,其中包含所有消息... –

+1

您可以先格式化您的源代碼嗎?這有點難以閱讀。 – LHCHIN

回答

0

聲明因出現異常對象列表類,然後收集。

import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 

public class dummy { 

    public static void main(String args[]) 

    { 
     String getEach = ""; 

     List<String> A = new ArrayList<String>(); 
     A.add("1"); 
     A.add("2"); 
     A.add("3"); 
     A.add("AA"); 
     A.add("4"); 
     A.add("5"); 
     A.add("dsfgfdsgfdshg"); 
     A.add("30"); 
     Iterator<String> map = A.iterator(); 
     List<Exception> errList = new ArrayList<Exception>(); 
     while (map.hasNext()) { 
      try { 
       getEach = map.next(); 
       int getValue = Integer.parseInt(getEach); 
       System.out.println("Value:::::: " + getValue); 
      } catch (Exception E) 
      { 

       //System.out.println("There is an exception c" + E.getMessage()); 
       errList.add(E); 
      } 
     } 

     if(!errList.isEmpty()) 
     { 
      for(Iterator<Exception> eIter = errList.iterator();eIter.hasNext();) 
      { 
       Exception e = eIter.next(); 

       System.out.println("There is an exception c" + e.getMessage()); 
      } 
     } 
    } 
} 
0

你可以我想剛落的try/catch完全和使用這樣的:

while(map.hasNext()) { 
    getEach = map.next(); 
    // If getEach contains the string representation of 
    // a Numerical value. The regular expression within 
    // the matcher below will handle signed, unsigned, 
    // integer, and double numerical values. If getEach 
    // holds a numerical value then print it. 
    if (getEach.matches("-?\\d+(\\.\\d+)?")) { 
     int getValue = Integer.parseInt(getEach); 
     System.out.println("Value:::::: "+getValue); 
    } 
}