Search code examples
androidandroid-studiokotlinillegalargumentexceptionterminate

Will IllegalArgumentException termination an app?


The following code is from the official sample project.

Will IllegalArgumentException termination the app when Result.Error(IllegalArgumentException("City doesn't exist")) is launched ?

sealed class Result<out R> {
    data class Success<out T>(val data: T) : Result<T>()
    data class Error(val exception: Exception) : Result<Nothing>()
}


class DetailsViewModel @Inject constructor(
    private val destinationsRepository: DestinationsRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val cityName = savedStateHandle.get<String>(KEY_ARG_DETAILS_CITY_NAME)!!

    val cityDetails: Result<ExploreModel>
        get() {
            val destination = destinationsRepository.getDestination(cityName)
            return if (destination != null) {
                Result.Success(destination)
            } else {
                Result.Error(IllegalArgumentException("City doesn't exist")) // Will IllegalArgumentException termination an app ?
            }
        }
}

Solution

  • The app will not crash (terminate) in this case, because the IllegalArgumentException exception is just being created, not thrown. The app will crash (terminate) if exception is thrown and isn't catched by try-catch operator, like the following:

    throw IllegalArgumentException("City doesn't exist")