Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJian Chen
4,938 PointsIf conditional in try/catch
Can someone please help me clarify why did Ben place this if conditional in this try/catch when all its doing is checking a boolean. What actually happens within those bottom lines of code there? I am having difficulty understanding what is happening, line by line around the try/catch area.
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String apiKey = "195c48bb49ff4037d809416a7b7ea3bf";
double latitude = 37.8267;
double longitude = -122.423;
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
"/" + latitude + "," + longitude;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(forecastUrl).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
}
@Override
public void onResponse(Response response) throws IOException {
try {;
if (response.isSuccessful()) {
Log.v(TAG, response.body().string());
}
} catch (IOException e) {
Log.e(TAG, "Exception ERROR: ", e);
}
}
});
}
}
jon1234
5,022 Pointsjon1234
5,022 PointsThe if statement only checks if the response is a success. The try/catch block is to handle errors that may arise while making the http request. If this code were not inside the try/catch block an IOException would cause the app to force close. For instance if the user lost network connection in the middle of the request, when the app tried to check
response would be null or not exist and cause an error.