⚠️ 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.
💡 Khái niệm
Phần tiêu đề “💡 Khái niệm”Kotlin sử dụng try-catch-finally giống Java, nhưng try là expression (có thể trả về giá trị).
val result = try { parseInt("123")} catch (e: NumberFormatException) { 0 // Default value}📝 Cú pháp cơ bản
Phần tiêu đề “📝 Cú pháp cơ bản”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")}⭐ try as Expression
Phần tiêu đề “⭐ try as Expression”val number = try { "123".toInt()} catch (e: NumberFormatException) { null}
// Elvis operator patternval safeNumber = try { input.toInt() } catch (e: Exception) { 0 }🔧 Throw Exception
Phần tiêu đề “🔧 Throw Exception”fun validateAge(age: Int): Int { if (age < 0) { throw IllegalArgumentException("Age cannot be negative") } return age}
// throw cũng là expressionval result = name ?: throw IllegalStateException("Name required")🎯 Result Pattern (Modern approach)
Phần tiêu đề “🎯 Result Pattern (Modern approach)”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) }}
// Usagewhen (val result = parseNumber("123")) { is Result.Success -> println("Number: ${result.data}") is Result.Failure -> println("Error: ${result.error.message}")}📦 runCatching (Kotlin stdlib)
Phần tiêu đề “📦 runCatching (Kotlin stdlib)”val result = runCatching { "123".toInt()}
result.getOrNull() // 123 hoặc nullresult.getOrDefault(0) // 123 hoặc 0result.getOrElse { -1 }
result.onSuccess { println("Value: $it") } .onFailure { println("Error: ${it.message}") }⚠️ Kotlin không có Checked Exceptions
Phần tiêu đề “⚠️ Kotlin không có Checked Exceptions”// Kotlin - không cần khai báo throwsfun readFile(path: String): String { return File(path).readText() // Có thể throw IOException}
// Java - phải khai báo// String readFile(String path) throws IOException { ... }✅ Checklist
Phần tiêu đề “✅ Checklist”- Sử dụng try-catch-finally
- Sử dụng try as expression
- Throw custom exceptions
- Sử dụng
runCatchingcho functional style - Hiểu Kotlin không có checked exceptions
Tiếp theo: File Operations