Middle — Middle+
What alternative error handling methods can be implemented besides catching exceptions with a try-catch block?
sobes.tech AI
Answer from AI
In addition to using try-catch for exception handling in Android, the following approaches can be applied:
- Checking conditions before performing operations — for example, verifying input data or network status to avoid errors.
- Using return values with error indicators — for example, returning null or a special result object with error information.
- Callback methods with error handling — in asynchronous operations, passing callbacks to handle success and errors.
- Using Result or Either types (in Kotlin) — for explicitly representing successful and erroneous 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}") }