12. Excepciones: Manejo de errores
try/catch/finally
Kotlin no tiene checked exceptions. El manejo es similar a Java pero más limpio:
try-catch.kt
KOTLIN
1 try {
2 val numero = "abc".toInt()
3 println(numero)
4 } catch (e: NumberFormatException) {
5 println("Error: no es un número válido")
6 } finally {
7 println("Esto siempre se ejecuta")
8 }
try como expresión
En Kotlin, try puede devolver un valor:
try-expresion.kt
KOTLIN
1 val resultado = try {
2 "42".toInt()
3 } catch (e: NumberFormatException) {
4 0 // valor por defecto
5 }
6 println(resultado) // 42
7
8 val texto = try {
9 "100".toInt()
10 } catch (e: Exception) {
11 -1
12 }
13 println(texto) // 100
Lanzar excepciones
Usa throw para crear excepciones personalizadas:
throw.kt
KOTLIN
1 fun dividir(a: Int, b: Int): Int {
2 if (b == 0) throw IllegalArgumentException("No se puede dividir por cero")
3 return a / b
4 }
5
6 try {
7 println(dividir(10, 0))
8 } catch (e: IllegalArgumentException) {
9 println(e.message) // "No se puede dividir por cero"
10 }
11
12 // Tipos comunes:
13 // IllegalArgumentException - argumento inválido
14 // IllegalStateException - estado inválido
15 // IndexOutOfBoundsException - índice fuera de rango
16 // NumberFormatException - conversión fallida
Seguridad con let
Combina null safety con manejo de errores:
safe-let.kt
KOTLIN
1 val input: String? = "42"
2
3 val numero = input?.toIntOrNull() ?: 0
4 println(numero) // 42
5
6 val invalido: String? = "abc"
7 val valor = invalido?.toIntOrNull() ?: -1
8 println(valor) // -1
💻 Misión
Crea una función `parsearEdad` que reciba un String y retorne un Int. Si falla, retorna -1. Pruébala con "25" y "abc".
👁️ Ver solución sugerida
main.kt
KOTLIN
1 fun parsearEdad(input: String): Int {
2 return try {
3 input.toInt()
4 } catch (e: NumberFormatException) {
5 -1
6 }
7 }
8
9 fun main() {
10 println(parsearEdad("25")) // 25
11 println(parsearEdad("abc")) // -1
12 }