通过swift的错误处理窥视其设计理念

案例

先来看一个例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
`enum VendingMachineError: ErrorType {
case InvalidSelection
case OutOfStock
}
struct Item {
var price: Int
var count: Int
}
class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func vend(itemName name: String) throws {
guard var item = inventory[name] else {
throw VendingMachineError.InvalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.OutOfStock
}
}
}
func buyFavoritesSnack(person: String, vendingMachine: VendingMachine) {
let snckName = "Candy Bar"
do {
try vendingMachine.vend(itemName: snckName)
} catch VendingMachineError.InvalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
print("Invalid OutOfStock.")
}
}

`在playground中运行会提示以下报错,但在do-try-catch中已经对定义的每种Error都进行了处理,为何还会提示没有穷举全部的Errors呢

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

分析

在Swift2 error handling 模型中,有两个重要的关键点:

  1. exhaustiveness(穷举)
  2. resiliency(弹性)

两者一起决定了do-catch需要处理所有可能的error,而不仅是自已定义的。上述例子中func vend 只是声明会抛出异常,并没有指明具体是异常种类。不允许指明具体异常体现了弹性的设计理念。假设将来出于其它目的增加了异常的种类,不希望每个调用方法的地方都要修改catch。调用者由于不知道vend会抛出种异常。基于穷举的设计理念,在catch自定义的error外,还要处理未知的error。

1
2
3
4
5
6
7
8
9
10
11
12
` do {
try vendingMachine.vend(itemName: snckName)
} catch VendingMachineError.InvalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
print("Invalid OutOfStock.")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
print("Invalid InsufficientFunds: \(coinsNeeded)")
} catch { //一定要增加处理未知error的通用catch 语句
print("universal error")
}

`

One More Thing

对于调用者来说,使用上面自定义的异常时,在每个catch处都要处理异常描述。意味着将来如果异常改变时,每个调用者也都要变,不够resiliency

比较好的做法是集中化处理Error描述:

1
2
3
4
5
6
7
8
`extension VendingMachineError: CustomStringConvertible {
var description: String {
switch self {
case .InvalidSelection: return "InvalidSelection"
case .OutOfStock: return "OutOfStock"
}
}
}

`加了这个extension后,调用者catch的异常就可以集中交给自己处理:

1
2
3
4
5
6
7
do {
try vendingMachine.vend(itemName: snckName)
} catch let error as VendingMachineError {
print(error.description)
} catch {
print("I dunno")
}

`

总结

Swift为了减少运行时的错误率,其异常处理机制要求我们必须处理出全部的异常,包括已知和未知的。同时又巧妙地添加了弹性特性,尽量减少修改代码对程序的影响。

参考资料: swift-do-try-catch-syntax