Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Weather App (2015) Concurrency and Error Handling Making Our Code Asynchronous

Jian Chen
Jian Chen
4,938 Points

If 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();

    protected void onCreate(Bundle savedInstanceState) {

        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() {
            public void onFailure(Request request, IOException e) {


            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);




The 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.