Skip to Content
Kotlin📘 Ngôn ngữ Kotlin⚠️ Exception Handling

Exception Handling trong Kotlin

🎯 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

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 }

📝 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

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

🔧 Throw Exception

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")

🎯 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) } } // Usage when (val result = parseNumber("123")) { is Result.Success -> println("Number: ${result.data}") is Result.Failure -> println("Error: ${result.error.message}") }

📦 runCatching (Kotlin stdlib)

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ó Checked Exceptions

// 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 { ... }

✅ Checklist

  • 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

Last updated on