IllegalArgumentException 会终止应用程序吗?
Will IllegalArgumentException termination an app?
以下代码来自官方示例project.
当 Result.Error(IllegalArgumentException("City doesn't exist"))
启动时,IllegalArgumentException
会终止应用程序吗?
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 ?
}
}
}
在这种情况下,应用程序不会崩溃(终止),因为 IllegalArgumentException
异常只是被创建,而不是被抛出。如果抛出异常并且未被 try-catch
运算符捕获,应用程序将崩溃(终止),如下所示:
throw IllegalArgumentException("City doesn't exist")
以下代码来自官方示例project.
当 Result.Error(IllegalArgumentException("City doesn't exist"))
启动时,IllegalArgumentException
会终止应用程序吗?
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 ?
}
}
}
在这种情况下,应用程序不会崩溃(终止),因为 IllegalArgumentException
异常只是被创建,而不是被抛出。如果抛出异常并且未被 try-catch
运算符捕获,应用程序将崩溃(终止),如下所示:
throw IllegalArgumentException("City doesn't exist")