捕获不同的错误类型
让我们为这个例子创建我们自己的错误类型。
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)
}