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 Handling Errors

Runkun Miao
Runkun Miao
4,186 Points

In this video, we've already had try-catch block but why we still add a if-else statement?

like the question above

1 Answer

Here is my take on the issue. Maybe a Guru can correct or validate :)

I will try to answer in two parts:

  1. Why use Try-Catch along with If-Else
  2. Why use try-catch for response.isSuccessful()

1. Why use Try-Catch along with If-Else Try-Catch is for exception handling where as If-Else is for logical reasoning.

Try-Catch will ensure that in case of any error during your logical reasoning (if-else), your entire app does not crash but instead allows for graceful exit.

Now, you could argue the other way around, which is, since we already have If-else on response.isSuccessful() why do we need try-catch? Which brings us to second point

2. Why use try-catch for response.isSuccessful() Because response.isSuccessful() throws IOException and you need to manage it using try-catch. Since *.enqueue() is an asynchronous call you are not sure when the entire response is ready for consumption. The callback is made after the response headers are ready. Reading the response body may still block.

Reading Material You can get some more information here:

Not sure if this answers or even helps, let me know if you find something on this.