We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am building a weather-station app by requesting JSON data from a weather website. When i have internet connection everything works fine but sometimes my internet drops and processing throws a 'ConnectException' which is to be expected because there is no internet available, i am trying to solve this issue by using try-catch as explained here : https://forum.processing.org/two/discussion/3158/solved-try-catch-not-found-in-processing-2-x-versions-help but it is not working because it says that 'ConnectException e' is an "Unreachable catch block for ConnectException.This exception is never thrown from the try statement body" but i have imported 'import java.net.ConnectException;' but it still does not work. Can anybody explain what i am doing wrong or what i should do to prevent the program from crashing when i loose internet connection?
code:
void update() {
try{
json = loadJSONObject("http://api.openweathermap.org/data/2.5/weather?q=Alcafache,PT&units=metric&appid=865339b01d84d874f8dc4857e5eb5f5c");
if(json != null){
JSONObject coord = json.getJSONObject("coord");
lon = coord.getFloat("lon");
lat = coord.getFloat("lat");
JSONObject sys = json.getJSONObject("sys");
sunR = sys.getInt("sunrise");
sunS = sys.getInt("sunset");
JSONObject main = json.getJSONObject("main");
temp = main.getFloat("temp");
pressure = main.getFloat("pressure");
humidity = main.getInt("humidity");
JSONObject wind = json.getJSONObject("wind");
windS = wind.getFloat("speed");
windD = wind.getFloat("deg");
JSONObject clouds = json.getJSONObject("clouds");
cloud = clouds.getInt("all");
JSONArray weather = json.getJSONArray("weather");
JSONObject mainCond = weather.getJSONObject(0);
ID = mainCond.getInt("id");
condition = mainCond.getString("main");
description = mainCond.getString("description");
icon = mainCond.getString("icon");
ImageAdress = "http://openweathermap.org/img/w/" + icon + ".png";
weatherIcon = loadImage(ImageAdress);
println(" INTERNET");
}
}catch(ConnectException e){
println("no Internet");
}
weather_counter = millis();
}
Answers
https://forum.Processing.org/two/discussion/8045/how-to-format-code-and-text
Most of Processing's functions "swallow" any thrown Exception.
In the case of loadJSONObject(), it "swallows" IOException.
However, an additional NullPointerException somehow slips from its buggy grasp.
Thus it's NullPointerException which should go into
catch ()
.Also, no need to wrap up big chunks of code inside
try
.Just focus the portion which really needs to be there: :-B
Thanks for the reply, i will integrate it into my program and give it a try, i assume that i can remove the code below, is this correct?
Yea, those extra lines were there just to force the error in loadJSONObject() to trigger. >-)
And make sure my custom loadJSON() function would successfully recover from it. :-\"