2017-09-25 152 views
-1

我有這樣的事情:不能捕捉異常

... 
while (itr.hasNext()) { 
... 
try { 

    if (userInput.equalsIgnoreCase(theData.getName()) 
     || (country.getName().toString()).equalsIgnoreCase(theData.getName())) 
     { 

     result = new Country(PointT, dist); 
     break; 

     } else { 

     for (int i = 0; i < repl.size(); i++) { 

      if (repl.get(i).toString().contains(theData.getName())) { 

      theName = true; 
      result = new Country(PointTt, dist, theName); 
      break; 
      } else if (theParts.get(i).toString().equalsIgnoreCase(theData.getName())) { 
      result = new Country(PointT, dist); 
      break; 
      } 
     } 


     } 
    } catch (NoSuchElementException ex) { 
     logger.error("Does not exist in database", ex); 
     throw ex; 
    } catch (NullPointerException ex) { 

     logger.error("Does not exist in database", ex); 
     throw ex; 
    }catch (Exception ex) { 
     logger.error("Does not exist in database", ex); 
     throw ex; 
    } 
} 
... 

所以,我用theData.getName()相比,userInput這僅僅是一個字符串,country.getName()這是也是一個字符串,repl.get(i)這是一個List<String>,theParts.get(i)這也是一個List<String>

我找不到解決方案來完成這項工作。在數據庫中不存在字符串(theData.getName())時拋出異常。

讀取數據

爲了讀取theData

我使用FileInputStream fis = new FileInputStream(filelocation);

然後,只提取的字符串,並將其儲存:

ArrayList<String> theNames = new ArrayList<String>();

,然後我將theNames與其他迭代器合併並創建

ArrayList<theNamesLoc> theNamesLocList = new ArrayList<theNamesLoc>();

而這正是我申請了數組列表:

Iterator<TheNamesLoc> itr = theNamesLocList.iterator(); 

while (itr.hasNext()) { 

..} 
+2

if(!next())throw ..?類似的東西?你不顯示你如何閱讀你的數據,那麼我們應該怎麼知道? – Stultuske

+0

是數據null?你在使用前先檢查它嗎? – Assafs

+1

if(theData == null)如何拋出xyzException? – procrastinator

回答

0

編輯:

假設REPL是在數據庫中的所有答覆都保存在列表中,有可以是兩種情況:

  1. 給定輸入是列表中任何字符串的一部分(例如:輸入是'xyz',列表包含元素'axyzw')。
  2. 輸入完全與列表中的其中一項匹配。

第一種情況:

boolean isPresent = false; 
for(String elem: list){ 
    if(elem.contains("xyz")){//check each string if it contains the element 
     isPresent = true; 
     break; 
    } 
} 
if(!isPresent){ 
    throw new NoSuchElementException("Element wasn't found in the list"); 
} 

第二種情況:

第二種情況是非常簡單的:

if(!list.contains("xyz")){ 
    throw new NoSuchElementException("Element not found"); 
} 

最終,你必須 「拋出」 的例外,這可隨後在任何需要的地方捕捉。

原來的答案:

如果我收到了你的問題的權利,你需要定義一個else塊「拋出」的例外。

if (repl.get(i).toString().contains(theData.getName())) { 
.... 
} else{ 
    throw new NoSuchElementException(args...); 
} 
+0

是的,但是當我有if-else-for-if語句時,我該如何實現這樣的事情? – George

+0

我使用了布爾標誌的組合並嘗試catch.Thanks – George