跳至正文

⚠️ 例外處理

📖 什麼是例外?

**例外(Exception)**是程式執行過程中發生的錯誤。妥善處理例外可以讓程式不會中斷並穩定運作!

💡 基本 try-catch

基本用法

fun main() {
try {
val result = 10 / 0 // 錯誤發生!
println(result)
} catch (e: Exception) {
println("錯誤發生:${e.message}")
}
// 錯誤發生:/ by zero

println("程式繼續執行!")
}

處理特定例外

fun main() {
try {
val text = "abc"
val number = text.toInt() // NumberFormatException
} catch (e: NumberFormatException) {
println("無法轉換為數字:${e.message}")
} catch (e: Exception) {
println("未知錯誤:${e.message}")
}
}

finally

fun main() {
try {
println("開始作業")
// 執行作業
} catch (e: Exception) {
println("發生錯誤")
} finally {
println("清理作業(總是執行)")
}
}

🎯 實戰範例

安全的數字轉換

fun safeToInt(text: String): Int? {
return try {
text.toInt()
} catch (e: NumberFormatException) {
null
}
}

fun main() {
println(safeToInt("123")) // 123
println(safeToInt("abc")) // null

val age = safeToInt("25") ?: 0
println("年齡:$age")
}

檔案讀取模擬

class FileReader {
fun readFile(filename: String): String {
if (filename.isEmpty()) {
throw IllegalArgumentException("檔案名稱為空")
}
if (!filename.endsWith(".txt")) {
throw IllegalArgumentException("僅支援文字檔案")
}
return "檔案內容:$filename"
}
}

fun main() {
val reader = FileReader()

try {
val content = reader.readFile("data.txt")
println(content)
} catch (e: IllegalArgumentException) {
println("錯誤:${e.message}")
}

try {
reader.readFile("")
} catch (e: IllegalArgumentException) {
println("錯誤:${e.message}")
// 錯誤:檔案名稱為空
}
}

使用者輸入驗證

data class User(val name: String, val age: Int)

fun createUser(name: String, age: Int): User {
require(name.isNotBlank()) { "姓名為必填" }
require(age > 0) { "年齡必須為正數" }
require(age < 150) { "年齡過大" }

return User(name, age)
}

fun main() {
try {
val user1 = createUser("洪吉童", 25)
println(user1)

val user2 = createUser("", 25) // 錯誤!
} catch (e: IllegalArgumentException) {
println("驗證失敗:${e.message}")
// 驗證失敗:姓名為必填
}
}

API 回應處理

sealed class Result<out T> {
data class Success<T>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
}

fun divide(a: Int, b: Int): Result<Int> {
return try {
Result.Success(a / b)
} catch (e: ArithmeticException) {
Result.Error(e)
}
}

fun main() {
val result1 = divide(10, 2)
when (result1) {
is Result.Success -> println("結果:${result1.data}")
is Result.Error -> println("錯誤:${result1.exception.message}")
}

val result2 = divide(10, 0)
when (result2) {
is Result.Success -> println("結果:${result2.data}")
is Result.Error -> println("錯誤:${result2.exception.message}")
}
}

🔍 作為表達式使用

try 作為值

fun main() {
val number = try {
"123".toInt()
} catch (e: NumberFormatException) {
0 // 預設值
}

println(number) // 123

val invalid = try {
"abc".toInt()
} catch (e: NumberFormatException) {
-1
}

println(invalid) // -1
}

鏈式呼叫

fun safeDivide(a: Int, b: Int): Int? {
return try {
a / b
} catch (e: ArithmeticException) {
null
}
}

fun main() {
val result = safeDivide(10, 2)
?.let { it * 2 }
?.let { it + 5 }
?: 0

println(result) // 15 (10/2 * 2 + 5)
}

🛡️ 撰寫安全的程式碼

require vs check

fun processOrder(quantity: Int, price: Int) {
// 輸入驗證
require(quantity > 0) { "數量必須為正數" }
require(price > 0) { "價格必須為正數" }

val total = quantity * price

// 狀態驗證
check(total < 1000000) { "總金額過大" }

println("訂單完成:${total}元")
}

fun main() {
try {
processOrder(10, 5000) // 成功
processOrder(-1, 5000) // require 失敗
} catch (e: IllegalArgumentException) {
println("輸入錯誤:${e.message}")
} catch (e: IllegalStateException) {
println("狀態錯誤:${e.message}")
}
}

checkNotNull

fun processName(name: String?) {
val validName = checkNotNull(name) { "姓名為 null" }
println("處理:$validName")
}

fun main() {
try {
processName("洪吉童") // 成功
processName(null) // 失敗
} catch (e: IllegalStateException) {
println("錯誤:${e.message}")
}
}

runCatching

Kotlin 1.3 開始提供的便利方法!

fun main() {
// 使用 runCatching
val result = runCatching {
"123".toInt()
}

result
.onSuccess { println("成功:$it") }
.onFailure { println("失敗:${it.message}") }

// getOrNull
val number = runCatching { "abc".toInt() }.getOrNull()
println(number) // null

// getOrDefault
val safe = runCatching { "abc".toInt() }.getOrDefault(0)
println(safe) // 0
}

🎯 實用模式

重試邏輯

fun <T> retry(times: Int, block: () -> T): T? {
repeat(times) { attempt ->
try {
return block()
} catch (e: Exception) {
println("第 ${attempt + 1} 次嘗試失敗:${e.message}")
if (attempt == times - 1) throw e
}
}
return null
}

fun main() {
var count = 0

try {
val result = retry(3) {
count++
if (count < 3) {
throw Exception("尚未完成")
}
"成功!"
}
println(result)
} catch (e: Exception) {
println("最終失敗")
}
}

資源清理

class Resource : AutoCloseable {
init {
println("建立資源")
}

fun use() {
println("使用資源")
}

override fun close() {
println("清理資源")
}
}

fun main() {
try {
Resource().use { resource ->
resource.use()
// 自動呼叫 close()
}
} catch (e: Exception) {
println("發生錯誤")
}
}

🤔 常見問題

Q1. throw 什麼時候使用?

**A:**明確要拋出例外時!

fun validateAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("年齡不能為負數")
}
if (age > 150) {
throw IllegalArgumentException("年齡過大")
}
}

Q2. Exception vs RuntimeException?

**A:**Kotlin 沒有區分!

// Java 中區分 checked/unchecked
// Kotlin 全部都是 unchecked(不需要宣告 throws)

fun divide(a: Int, b: Int): Int {
return a / b // 不需要宣告 throws!
}

Q3. 自訂例外?

**A:**繼承 Exception!

class InvalidEmailException(message: String) : Exception(message)

fun validateEmail(email: String) {
if (!email.contains("@")) {
throw InvalidEmailException("無效的電子郵件:$email")
}
}

fun main() {
try {
validateEmail("invalid")
} catch (e: InvalidEmailException) {
println(e.message)
}
}

🎬 總結

透過例外處理建立穩定的程式!

核心重點:
✅ 使用 try-catch 處理例外
✅ 使用 require/check 驗證
✅ 使用 runCatching 簡化處理
✅ 作為表達式回傳值
✅ 使用 finally 進行清理作業

下一步:在檔案輸入輸出中學習如何處理檔案!