简体   繁体   English

如何忽略异常并继续下一个值

[英]how to ignore the exception and continue to next value

Hi I am trying to pass the list of values to google api.If the api throws any exceptions, it comes out of the loop.I need to coninue to next value even if throws any error.My code below. 嗨,我正在尝试将值列表传递给google api。如果api抛出任何异常,它将退出循环。即使抛出任何错误,我也需要继续下一个值。我的代码如下。

while (iterator.hasNext()) {
       Object element = iterator.next();
       String postcode = element.toString().trim();
       String latLongs[] = getLatLongPositions(postcode);
       System.out.println("Latitude: " + latLongs[0] + " and Longitude: " + latLongs[1]);
       System.out.println(postcode);
   }

   public static String[] getLatLongPositions(String address) throws Exception {

       int responseCode = 0;
       String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
       URL url = new URL(api);
       HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
       httpConnection.connect();
       responseCode = httpConnection.getResponseCode();
       if (responseCode == 200) {
           DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
           org.w3c.dom.Document document = builder.parse(httpConnection.getInputStream());
           XPathFactory xPathfactory = XPathFactory.newInstance();
           XPath xpath = xPathfactory.newXPath();
           XPathExpression expr = xpath.compile("/GeocodeResponse/status");
           String status = (String) expr.evaluate(document, XPathConstants.STRING);
           if (status.equals("OK")) {
               expr = xpath.compile("//geometry/location/lat");
               String latitude = (String) expr.evaluate(document, XPathConstants.STRING);
               expr = xpath.compile("//geometry/location/lng");
               String longitude = (String) expr.evaluate(document, XPathConstants.STRING);
               return new String[] {
                   latitude, longitude
               };
           } else {

               throw new Exception("Error from the API - response status: " + status);
           }
       }
       return null;
   }

even If I mention return null instead of throw new exception.It shows null pointer exception.any help will be appreciated. 即使我提到返回null而不是抛出新异常,它也显示了null指针异常,我们将不胜感激。

put try/catch around this part 尝试/抓住这部分

...
try{
    String latLongs[] = getLatLongPositions(postcode);
    System.out.println("Latitude: " + latLongs[0] + " and Longitude: " + latLongs[1]);
    System.out.println(postcode);
}catch(Exception e){
    ...
}

Try 尝试

else {
               try {
            throw new Exception ("Error from the API - response status: " + status);
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
    }

You should put those statements where you expect an exeption to happen in a try block and process those exceptions in a catch block. 您应该将这些语句放在希望发生异常的地方,放在try块中,并在catch块中处理那些异常。

try {
 // statement where an exception may occur
}
catch ( SomeTypeOfException e ) {
 // will be processed if this particular exception occured
} 
catch ( Exception e )  {
 // process any exception
}
finally {
 // do this regardless of what happened in the try block
}

To clarify: the try..catch statement creates a block of code in which, should an exception occur, that exception will be "caught." 需要说明的是: try..catch语句创建一个代码块,如果发生异常,该代码块将被“捕获”。 (You can nest these statements, and, in the catch block, specify specific exception-types that you wish to catch ...) (您可以嵌套这些语句,并在catch块中指定要捕获的特定异常类型...)

After the statement completes (unless you "re-raise" an exception within the catch ...), the exception is "gone." 语句完成后(除非您在catch “重新引发”一个异常...),该异常为“已消失”。

There are plenty of examples of how this statement works, eg in the Java documentation itself. 关于此语句如何工作的示例很多, 例如在Java文档本身中。 (And, for the record, almost every programming language out there supports some flavor of this essential concept.) (据记录,几乎每种编程语言都支持这种基本概念。)

Note that you must put the entire try..catch statement fully inside the loop. 请注意,您必须将整个 try..catch语句完全放入循环中。 Do not attempt to "continue the loop" from the catch handler. 不要尝试从catch处理程序中“继续循环”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM