2013-10-11 24 views
0

的身體扔我收到一個錯誤每次。我究竟做錯了什麼?錯誤:異常IOException,而從來沒有在相應的try語句

我的代碼:

public static void hashMap(String crnString) 
{ 
    try 
    { 
     if (mMap.containsKey(crnString)) 
     { 
      int count = mMap.get(crnString); 
      count++; 
      mMap.put(crnString, count); 
     } 
     else 
     { 
      mMap.put(crnString, 1); 
     } 
    } 
    catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 
    finally 
    { 
    } 
} 
+0

請格式化你的代碼。 –

+1

這裏沒有'語法錯誤'。你'收到一個錯誤'這是一個*編譯錯誤,*哪些*告訴你*什麼是錯的。不要只是在這裏發佈'我收到一個錯誤',不說這是什麼:這是不可接受的;並且不要忽略錯誤實際所說的內容。在這種情況下,就像在很多情況下,它已經回答你的問題。 – EJP

+4

聽起來你今天過得很糟糕,明天會有更好的一天。 – GirlWhoCodes

回答

2

假設mMapHashMap,所述try塊內的代碼從不拋出IOException。刪除包裝你的代碼的try-catch塊。

public static void hashMap(String crnString){ 
    if (mMap.containsKey(crnString)) { 
     int count = mMap.get(crnString); 
     count++; 
     mMap.put(crnString, count); 
    } else { 
     mMap.put(crnString, 1); 
    } 
} 
+0

我該如何打印hashmap?此代碼是否可以工作? 。 – GirlWhoCodes

+0

公共靜態無效printHash(){ \t \t迭代iter1 = mMap.entrySet()迭代(); (iter1.hasNext()){ \t \t \t Map.Entry mEntry =(Map.Entry)iter1.next(); \t \t \t的System.out.println(mEntry.getKey()+ 「:」 + mEntry.getValue()); \t \t \t \t \t} \t} – GirlWhoCodes

+0

@CPR這看起來是正確的。你最好的選擇是嘗試一下。 –

1

IOException是檢查異常。因此,try塊中的代碼不是可以引發IOExcption的潛在代碼,這就是編譯器顯示錯誤的原因。使用可以引發的特定異常類型catch塊或使用未經檢查的異常catch塊。在你嘗試阻止代碼時,只能提出NPE。

try 
{ 
    if (mMap.containsKey(crnString)) 
    { 
     int count = mMap.get(crnString); 
     count++; 
     mMap.put(crnString, count); 
    } 
    else 
    { 
     mMap.put(crnString, 1); 
    } 
} catch (NullPointerException e) 
{ 
    e.printStackTrace(); 
} catch(Exception e) { 
    System.out.println("Unexcepted Exception"); 
    e.printStackTrace(); 
} 
finally 
{ 
} 
+1

謝謝你居然幫我 – GirlWhoCodes

+0

請問此代碼的工作:\t公共靜態無效printHash(){ \t \t迭代iter1 = mMap.entrySet()迭代器(); (iter1.hasNext()){ \t \t \t Map.Entry mEntry =(Map.Entry)iter1.next(); \t \t \t的System.out.println(mEntry.getKey()+ 「:」 + mEntry.getValue()); \t \t \t \t \t} \t} – GirlWhoCodes

相關問題