在swift中 如果我们要定义一个表示错误类型非常简单,只要遵循Error协议就可以了,我们通常用枚举或者结构体来表示错误类型,枚举可能用的多些,因为他能更直观的表达当前错误类型的每种错误细节。
// // AboutError.swift // learn_swiftUi // // Created by liuan on 2020/9/4. // Copyright © 2020 liuan. All rights reserved. // import Foundation enum VendingMachingError:Error{ case invalideSelection case insufficientFunds(coinsNeeded:Int) case outOfStock }
函数、方法和初始化器都可以抛出错误。需要在参数列表后面,返回值加throws 关键字。
简化版
func canThrowErrors() throws -> String
// // AboutError.swift // learn_swiftUi // // Created by liuan on 2020/9/4. // Copyright © 2020 liuan. All rights reserved. // import Foundation enum VendingMachingError:Error{ case invalideSelection case insufficientFunds(coinsNeeded:Int) case outOfStock } struct Item { var price: Int var count: Int } class VendingMathine{ 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(itemNaamed name:String) throws{ guard let item = inventory[name] else{ throw VendingMachingError.invalideSelection } guard item.count > 0 else{ throw VendingMachingError.outOfStock } guard item.price <= coinsDeposited else{ throw VendingMachingError.insufficientFunds(coinsNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price var newItem = item newItem.count -= 1 inventory[name]=newItem print("Dispensing \(name)") } } let vm=VendingMathine() vm.coinsDeposited=2 try vm.vend(itemNaamed: "Pretzels")
抛出异常
Playground execution terminated: An error was thrown and was not caught: ▿ VendingMachingError ▿ insufficientFunds : 1 element - coinsNeeded : 5
在Swift中我们使用do-catch块对错误进行捕获,当我们在调用一个throws声名的函数或方法时,我们必须把调用语句放在do语句块中,同时do语句块后面紧接着使用catch语句块
do里面执行调用语句
后面跟着catch 第一种错误 在第一种错误里面做处理
第二种错误需要符合一定的条件
然后做错误处理
第三种是没有捕获到的错误 然后在第三个语句里面做处理
如果你确信一个函数或者方法不会抛出错误,可以使用try! 来中断错误的传播,但是如果错误真的发生了。你会得到一个运行时错误
// // AboutError.swift // learn_swiftUi // // Created by liuan on 2020/9/4. // Copyright © 2020 liuan. All rights reserved. // import Foundation let photo = try! 5/0
warning: BlackMyPlayground.playground:10:19: warning: no calls to throwing functions occur within 'try' expression let photo = try! 5/0 ^ warning: BlackMyPlayground.playground:10:19: warning: no calls to throwing functions occur within 'try' expression let photo = try! 5/0 ^ error: BlackMyPlayground.playground:10:19: error: division by zero let photo = try! 5/0 ^
defer关键字:defer block 例的代码会在函数return之前执行,无论函数是从哪个分之return的,还有throw,还是自然而然走到最后一样。
// // File.swift // learn_swiftUi // // Created by liuan on 2020/9/4. // Copyright © 2020 liuan. All rights reserved. // import Foundation func processFile(fileName: String)throws{ defer{ print("JIESHU") } print("KAISHI ") }