2017-09-25 155 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