Middle — Middle+
Millised alternatiivsed vigade käsitlemise viisid võivad olla rakendatavad, välja arvatud erandite püüdmine try-catch ploki abil?
sobes.tech AI
Vastus AI-lt
In addition to using try-catch for exception handling in Android, the following approaches can be applied:
- Checking conditions before performing operations — for example, validating input data or network status to prevent errors.
- Using return values with error indicators — for example, returning null or a special result object containing error information.
- Error handling callback methods — in asynchronous operations, callbacks can be passed to handle success and errors.
- Using Result or Either types (in Kotlin) — to explicitly represent successful and error results.
- Logging and monitoring — to track errors without interrupting the application's operation.
Example using Kotlin Result:
fun parseInt(str: String): Result<Int> {
return try {
Result.success(str.toInt())
} catch (e: NumberFormatException) {
Result.failure(e)
}
}
val result = parseInt("123")
result.onSuccess { println("Parsed number: $it") }
.onFailure { println("Error: ${it.message}") }