try
好的 👍
Swift 的 try 系列關鍵字主要用來處理 throwing functions(會丟出錯誤的函式)。
我幫你整理成表格,讓你一眼看懂差別:
Swift 錯誤處理中的 try 用法
| 語法 | 說明 | 錯誤發生時行為 | 適用情境 |
|---|---|---|---|
try | 最標準的用法,需要搭配 do { ... } catch { ... } | 錯誤會被傳遞給外層 catch | 正常需要錯誤處理的情境 |
try? | 會將回傳值轉成 optional,若發生錯誤則變成 nil | 不會 throw,也不會 crash | 當錯誤發生時可以接受「無值」就好 |
try! | 強制執行,不做錯誤處理 | 若真的 throw → 直接 runtime crash | 你能保證一定不會錯誤,例如 Demo 或測試環境 |
try await | 搭配 async function 使用的 try | 同 try,只是用在 async/await 語境 | 處理 async throwing function |
| rethrows + try | 當函式只會在傳入的 closure 可能 throw 時才會 throw | 視 closure 決定 | 高階函式(像 map, filter) |
範例程式
enum FileError: Error {
case notFound
}
func loadFile(name: String) throws -> String {
if name == "exists" {
return "File Content"
} else {
throw FileError.notFound
}
}
// 1. try + do-catch
do {
let content = try loadFile(name: "exists")
print(content)
} catch {
print("Error:", error)
}
// 2. try? → Optional
let safeContent = try? loadFile(name: "notFound")
print(safeContent) // nil
// 3. try! → 強制執行(錯誤會 crash)
let forceContent = try! loadFile(name: "exists")
print(forceContent)
// 4. try await → async throwing function
func fetchData() async throws -> String {
return "Data from server"
}
Task {
let data = try await fetchData()
print(data)
}