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 trial

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.

MainActivity.java
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);
                }

            }
        });


    }

}

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

if(response.isSuccessful()){
}

response would be null or not exist and cause an error.