Day95 of #100DaysOfCode
Hii folks 🙌
Today I will be continuing the same pathway in which we will learn about Exception Handling.
Unit 4: Internet
Pathway 2: Get and Display Data
https://developer.android.com/courses/android-basics-kotlin/course
Exception Handling
Exceptions are errors that can occur during the runtime(not compile time) and terminate the app abruptly without notifying the user. This can result in a poor user experience. Exception handling is a mechanism by which we prevent the app from terminating abruptly, and handle it in a user-friendly way.
The reason for exceptions could be as simple as division by zero or an error in the network. These exceptions are similar to the NumberFormatException
Examples of potential issues while connecting to a server:
- The URL or URI used in the API is incorrect.
- The server is unavailable and the app could not connect to it.
- Network latency issue.
- Poor or no internet connection on the device.
These exceptions can’t be caught during the compile time. We can use a try-catch
block to handle the exception in runtime.
Example syntax for try-catch block
try {
// some code that can cause an exception.
}
catch (e: SomeException) {
// handle the exception to avoid abrupt termination.
}
Inside the try
block we perform the code where we anticipate an exception, in our app this would be a network call. In the catch
block, we will implement the code that prevents abrupt termination of the app. If there is an exception, the catch
block will be executed to recover from the error instead of terminating the app abruptly.
- We will open
overview/OverviewViewModel.kt
. Scroll down to thegetMarsPhotos()
method. Inside the launch block, add atry
block aroundMarsApi
call to handle exceptions. Then addcatch
block after thetry
block:
viewModelScope.launch {
try {
val listResult = MarsApi.retrofitService.getPhotos()
_status.value = listResult
} catch (e: Exception) {
}
}
- Inside the
catch {}
block, we will handle the failure response. Then we will display the error message to the user by setting thee.message
to the_status.value
.
catch (e: Exception) {
_status.value = "Failure: ${e.message}"
}
- Then we will run the app again, with the airplane mode turned on. The app does not close abruptly this time but displays an error message instead.
- We will then turn off airplane mode on the emulator. We will run and test the app, make sure everything is working fine and we are able to see the JSON string.
That is all for Day95 ✅
Thanks for reading, See you tomorrow!