Swift:Errors thrown from here are not handled because the enclosing catch is not exhaustive

weixin_34128411發表於2016-12-21

在學習 Swift 錯誤處理的時候,官方給出的 do-catch 例子如下:

...
...

let favoriteSnacks = [
    "Alice": "Chips",
    "Bob": "Licorice",
    "Eve": "Pretzels",
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
    let snackName = favoriteSnacks[person] ?? "Candy Bar"
    try vendingMachine.vend(itemNamed: snackName)
}

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
    print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
}
// Prints "Insufficient funds. Please insert an additional 2 coins."

但是親自上手敲程式碼的時候,卻總是在 "do" 閉包中 try 語句上報錯:

"Errors thrown from here are not handled because the enclosing catch is not exhaustive"

301227-175fde9f87d1b496.png
1.png

大體意思是說這個 do-catch 是不完整的。這時候需要再加上一個空的 catch 語句用於關閉 catch。

do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.invalidSelection {
    print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
    print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
    print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
} catch { // 加入一個空的catch,用於關閉catch。否則會報錯:Errors thrown from here are not handled because the enclosing catch is not exhaustive

}

相關文章