美文网首页
Swift 错误处理和调试详解

Swift 错误处理和调试详解

作者: WSJay | 来源:发表于2018-08-10 18:30 被阅读0次

1.表示和抛出错误

在Swift中,错误由符合Error协议的类型的值表示。这个空协议表示类型可以用于错误处理。
Swift枚举特别适合于对一组相关错误条件进行建模,还可以给相关值添加错误性质的附加信息。

enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}

使用关键字throw表示,待执行语句抛出的错误信息。

throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

2.处理错误

(1).使用抛出函数传播错误

  • 使用关键字throws表示函数,方法,或构造器可以抛出错误;
  • throws添加在函数声明的参数后面,返回箭头->之前;
  • 抛出函数在执行是,将其中抛出的错误传播到调用它的范围;
func canThrowErrors() throws -> String

注意:只有抛出函数才能传播错误。非throwing函数抛出的任何错误,必须在函数内部处理;

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(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)
        }

        coinsDeposited -= item.price

        var newItem = item
        newItem.count -= 1
        inventory[name] = newItem

        print("Dispensing \(name)")
    }
}

vend(itemNamed:方法内部并没有处理错误,而是直接将抛出的错误传播出去。其他调用该方法的代码必需使用do-catch语句,try?try!,或继续传播错误等方式处理这些错误。

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)
}

buyFavoriteSnack(person: vendingMachine:)也是
一个抛出函数,它内部调用的vend(itemNamed:方法会抛出错误,因此在方法执行前面添加关键字try来调用。

如抛出函数一样,抛出构造器也可以按同样的方式传播错误。

struct PurchasedSnack {
    let name: String
    init(name: String, vendingMachine: VendingMachine) throws {
        try vendingMachine.vend(itemNamed: name)
        self.name = name
    }
}

(2).使用 Do-Catch处理错误
通过运行代码块,可以使用do-catch语句来处理错误。如果do闭包中的代码抛出了错误,它将与catch闭包匹配,以确定哪一个可以处理错误。

do {
    try expression
    statements
} catch pattern 1 {
    statements
} catch pattern 2 where condition {
    statements
} catch {
    statements
}

可以在catch之后编写要处理的错误模式,以指示闭包可以处理哪些错误。如果catch闭包没有相匹配的错误模式,则将错误交给最后的catch闭包来处理,并将错误绑定到名为error的本地常量中。

var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
    try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
    print("Success! Yum.")
} 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 {
    print("Unexpected error: \(error).")
}
// Prints "Insufficient funds. Please insert an additional 2 coins."

在上面的例子中,buyFavoriteSnack(person:vendingMachine:)函数在try表达式中调用,因为他会抛出错误。当有错误抛出时,就立刻转到相应的catch闭包中处理错误。若没有错误,则继续执行do闭包中的剩下语句。

这些catch闭包不必处理do闭包中的代码可能抛出的所有错误。如果没有catch闭包处理错误,则错误将传播到周围的范围。但是,传播的错误必须由周围的某个范围处理。在非抛出函数中,包含do-catch的闭包必须处理错误。在抛出函数中,要么包含do-catch闭包,要么调用方必须处理错误。如果错误传播到顶级范围而不被处理,将出现运行时错误。

func nourish(with item: String) throws {
    do {
        try vendingMachine.vend(itemNamed: item)
    } catch is VendingMachineError {
        print("Invalid selection, out of stock, or not enough money.")
    }
}

do {
    try nourish(with: "Beet-Flavored Chips")
} catch {
    print("Unexpected non-vending-machine-related error: \(error)")
}
// Prints "Invalid selection, out of stock, or not enough money."

(3).将错误转换为可选值

可以使用try?通过将错误转换为可选值来处理错误。如果在执行try?表达式时抛出错误,则表达式的值将为nil。

func someThrowingFunction() throws -> Int {
    // ...
}

let x = try? someThrowingFunction()

let y: Int?
do {
    y = try someThrowingFunction()
} catch {
    y = nil
}

当你想用同样的方式来处理所有的错误时,使用try?可以让你写出简洁的错误处理代码。
若下例所示,如果所有方法都失败,则返回nil:

func fetchData() -> Data? {
    if let data = try? fetchDataFromDisk() { return data }
    if let data = try? fetchDataFromServer() { return data }
    return nil
}

(4).禁用错误传播
有时你知道抛出函数或方法不会在运行时抛出错误。在这种情况下,你可以在表达式前面添加try!来禁止错误的传播,并将调用包装在运行时断言中,断言不会抛出错误。
如果实际抛出了一个错误,将得到一个运行时错误。

let photo = try! loadImage(atPath: "./Resources/John Appleseed.jpg")

3.指定清理操作

  • defer语句所在的代码块,无论是以何种方式结束执行(如抛出错误,break或return语句), defer中的代码始终都会被执行,且最后执行;
  • 当多个defer语句在同一代码块中时,它被执行的顺序与其在源代码中写入的顺序相反(即源代码顺序中的最后一个defer语句首先执行);
    例如,使用defer语句来确保关闭了文件描述符并释放手动分配的内存。
func processFile(filename: String) throws {
    if exists(filename) {
        let file = open(filename)
        defer {
            close(file)
        }
        while let line = try file.readline() {
            // Work with the file.
        }
        // close(file) is called here, at the end of the scope.
    }
}

4.断言和先决条件

  • 断言和先决条件是在运行时发生的检查。
  • 如果断言或先决条件中的布尔值为true,则代码将继续正常执行。如果为false,则程序的当前状态无效; 代码执行结束,应用程序终止。
  • 断言可以在开发过程中发现错误和错误的假设;先决条件可以检测生产中的问题。
  • 断言和先决条件与上述错误处理中讨论的错误条件不同,它们不用于可恢复的或预期的错误。因为失败的断言或先决条件表示无效的程序状态,所以无法捕获失败的断言。
  • 使用断言和先决条件执行有效的数据和状态,可以使应用程序在出现无效状态时更容易终止,易于调试问题。
  • 断言和先决条件之间的区别在于何时检测它们:断言只在调试版本中检查,而先决条件在调试和生产版本中都检查。在生产版本中,不进行评估断言中的条件。这意味着可以在开发过程中使用任意数量的断言,而不会影响生产中的性能。

(1).使用断言调试
从Swift标准库中调用assert(_:_:file:line:)函数来编写断言。向此函数传递给一个表达式,该表达式求值为truefalse。如果条件的结果为false,则显示一条消息。
例如:

let age = -3
assert(age >= 0, "A person's age can't be less than zero.")
// This assertion fails because -3 is not >= 0.

可以省略断言消息 - 例如:

assert(age >= 0)

若代码已经检查了条件,则使用assertionFailure(_:file:line:)函数来指明断言已失败。例如:

if age > 10 {
    print("You can ride the roller-coaster or the ferris wheel.")
} else if age > 0 {
    print("You can ride the ferris wheel.")
} else {
    assertionFailure("A person's age can't be less than zero.")
}

(2).执行先决条件
当条件可能为假时,但是为了能够使代码继续执行,条件必须为真,则使用先决条件。
可以通过调用precondition(_:_:file:line:)函数来编写先决条件。向该函数传递一个计算结果为真或假的表达式,并在条件结果为假时显示一条消息。例如:

// In the implementation of a subscript...
precondition(index > 0, "Index must be greater than zero.")

还可以调用preconditionFailure(_:file:line:)函数来指明失败发生时——例如,如果选择了开关的默认情况,但是所有有效的输入数据应该由开关的其中一种情况处理。

5.致命错误

  • 无条件输出给定的错误消息并停止执行。
//message: 要打印的字符串
//file: 输出“message”的文件名
//line:输出“message”的行号
public func fatalError(_ message: @autoclosure () -> String = default, file: StaticString = #file, line: UInt = #line) -> Never

6.其他专题模块

Swift 4.2 基础专题详解

相关文章

网友评论

      本文标题:Swift 错误处理和调试详解

      本文链接:https://www.haomeiwen.com/subject/ddbcbftx.html