捕獲不同的錯誤型別

讓我們為這個例子建立我們自己的錯誤型別。

Version = 2.2

enum CustomError: ErrorType {
    case SomeError
    case AnotherError
}

func throwing() throws {
    throw CustomError.SomeError
}

Version = 3.0

enum CustomError: Error {
    case someError
    case anotherError
}

func throwing() throws {
    throw CustomError.someError
}

Do-Catch 語法允許捕獲丟擲的錯誤,並自動catch 塊中建立一個名為 error 的常量:

do {
    try throwing()
} catch {
    print(error)
}

你也可以自己宣告變數:

do {
    try throwing()
} catch let oops {
    print(oops)
}

它也可以連結不同的 catch 語句。如果可以在 Do 塊中丟擲幾種型別的錯誤,這很方便。

在這裡,Do-Catch 將首先嚐試將錯誤轉換為 CustomError,然後如果自定義型別不匹配則將其作為 NSError

Version = 2.2

do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch let error as NSError {
    print(error)
}

Version = 3.0

在 Swift 3 中,無需明確向下轉換為 NSError。

do {
    try somethingMayThrow()
} catch let custom as CustomError {
    print(custom)
} catch {
    print(error)
}