gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:26:22 24 4
gpt4 key购买 nike

嗨,我正在尝试将值列表传递给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;
}

即使我提到返回 null 而不是抛出新异常。它也会显示空指针异常。任何帮助将不胜感激。

最佳答案

在这部分放置 try/catch

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

关于java - 如何忽略异常并继续下一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38828832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com