Skip to Content
Kotlin📘 Ngôn ngữ KotlinException Handling (try-catch)

Exception Handling trong Kotlin (try-catch)

1. Giới thiệu

Kotlin sử dụng try-catch để xử lý exceptions. Tất cả exceptions đều unchecked.

2. try-catch cơ bản

fun main() { try { val result = 10 / 0 println(result) } catch (e: ArithmeticException) { println("Cannot divide by zero: ${e.message}") } }

3. Nhiều catch blocks

fun parseInput(input: String): Int { return try { input.toInt() } catch (e: NumberFormatException) { println("Invalid number format") 0 } catch (e: Exception) { println("Unknown error: ${e.message}") -1 } }

4. finally block

fun readFile(path: String): String { val reader = File(path).bufferedReader() return try { reader.readText() } catch (e: IOException) { "Error reading file" } finally { reader.close() println("Reader closed") } }

5. try là expression

fun main() { val input = "123" val number: Int = try { input.toInt() } catch (e: NumberFormatException) { 0 } println(number) // 123 }

6. throw exception

fun validateAge(age: Int) { if (age < 0) { throw IllegalArgumentException("Age cannot be negative") } if (age > 150) { throw IllegalArgumentException("Age seems unrealistic") } } fun main() { try { validateAge(-5) } catch (e: IllegalArgumentException) { println("Error: ${e.message}") } }

7. Custom Exception

class InsufficientFundsException( val available: Double, val requested: Double ) : Exception("Insufficient funds: available=$available, requested=$requested") class BankAccount(private var balance: Double) { fun withdraw(amount: Double) { if (amount > balance) { throw InsufficientFundsException(balance, amount) } balance -= amount } }

8. Nothing type

fun fail(message: String): Nothing { throw IllegalStateException(message) } fun main() { val name: String = null ?: fail("Name is required") // Compiler biết code sau fail() không bao giờ chạy }

9. require, check, error

fun processUser(user: User?) { // Ném IllegalArgumentException nếu false requireNotNull(user) { "User cannot be null" } require(user.age >= 0) { "Age must be non-negative" } // Ném IllegalStateException nếu false check(user.isActive) { "User must be active" } // Ném IllegalStateException if (!user.isVerified) { error("User must be verified") } }

10. runCatching

fun main() { val result = runCatching { "hello".toInt() } result.onSuccess { value -> println("Got: $value") }.onFailure { exception -> println("Error: ${exception.message}") } // Hoặc val value = result.getOrDefault(0) val valueOrNull = result.getOrNull() }

📝 Tóm tắt

  • try-catch-finally xử lý exceptions
  • try là expression, trả về giá trị
  • Không có checked exceptions
  • throw ném exception
  • require, check cho validation
  • runCatching cho functional error handling
Last updated on