Swift4语法极简手册 — Error Handling

Swift4语法极简手册

第十八章节:Error Handling

Error Handling

Swift4中的错误处理机制

如何定义

如果一个方法可能会抛出错误,则按照如下格式来定义

1
2
3
4
//在方法名及参数值后加上throws,表示方法可能会抛出错误
func canThrowErrors() throws -> String {
//some thing
}

定义错误类型

1
2
3
4
5
6
//实现Error协议
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}

参考示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func vend(itemNamed name: String) throws {
guard let item = inventory[name] else {
throw VendingMachineError.invalidSelection
}
guard item.count > 0 else {
throw VendingMachineError.outOfStock
}
guard item.price <= coinsDeposited else {
throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
//do some thing
}

Handling Errors

有四种方式可以处理异常

try

这种方式就是不处理错误,把错误再抛出去给上一层调用者来处理

1
2
3
4
5
6
7
8
struct PurchasedSnack {
let name: String
init(name: String, vendingMachine: VendingMachine) throws {
//try 不捕获错误,throws出去,调用init方法的调用者需处理
try vendingMachine.vend(itemNamed: name)
self.name = name
}
}

do-try

这种是主动处理错误

1
2
3
4
5
6
7
8
9
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.")
}

try!

这种是相信一定不会报错

1
2
//虽然loadImage定义了会throws错误,但我肯定我调用的这个不会
let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

如果使用了try!又报错了,则闪退,因此一定要确认不会抛错才使用这种方式

try?

懒惰型,抛错就返回nil,懒得处理各种情况

1
2
//如果someThrowingFunction抛错,则x值为nil
let x = try? someThrowingFunction()