Bỏ qua để đến nội dung

⚠️ Exception Handling

🎯 Mục tiêu: Hiểu cách xử lý exceptions trong Kotlin với try-catch-finally và các patterns hiện đại.


Kotlin sử dụng try-catch-finally giống Java, nhưng tryexpression (có thể trả về giá trị).

val result = try {
parseInt("123")
} catch (e: NumberFormatException) {
0 // Default value
}

try {
// Code có thể throw exception
val result = 10 / 0
} catch (e: ArithmeticException) {
println("Cannot divide by zero: ${e.message}")
} catch (e: Exception) {
println("Other error: ${e.message}")
} finally {
println("Always executed")
}

val number = try {
"123".toInt()
} catch (e: NumberFormatException) {
null
}
// Elvis operator pattern
val safeNumber = try { input.toInt() } catch (e: Exception) { 0 }

fun validateAge(age: Int): Int {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
return age
}
// throw cũng là expression
val result = name ?: throw IllegalStateException("Name required")

sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Failure(val error: Throwable) : Result<Nothing>()
}
fun parseNumber(s: String): Result<Int> {
return try {
Result.Success(s.toInt())
} catch (e: Exception) {
Result.Failure(e)
}
}
// Usage
when (val result = parseNumber("123")) {
is Result.Success -> println("Number: ${result.data}")
is Result.Failure -> println("Error: ${result.error.message}")
}

val result = runCatching {
"123".toInt()
}
result.getOrNull() // 123 hoặc null
result.getOrDefault(0) // 123 hoặc 0
result.getOrElse { -1 }
result.onSuccess { println("Value: $it") }
.onFailure { println("Error: ${it.message}") }

// Kotlin - không cần khai báo throws
fun readFile(path: String): String {
return File(path).readText() // Có thể throw IOException
}
// Java - phải khai báo
// String readFile(String path) throws IOException { ... }

  • Sử dụng try-catch-finally
  • Sử dụng try as expression
  • Throw custom exceptions
  • Sử dụng runCatching cho functional style
  • Hiểu Kotlin không có checked exceptions

Tiếp theo: File Operations