Swift学习笔记十四之错误处理

1、错误处理:swift在运行时能够对错误进行处理并给出相应的操作
//处理错误的几种方式:
a、把错误传递给调用函数,然后使用do-catch语句处理错误
b、将错误作为可选类型处理
c、使用断言处理
//定义错误类型
enum CustomErrorType: Error{//通过枚举构建一组相关的错误状态
case errorReason1
case errorReason2
case errorReason3
}

2、通过throwing函数传递错误
//throwing函数:在参数列表后面加throws,表示可以抛出错误
// throwing函数: 在参数列表后面加throws,表示可以抛出错误
class ThrowClass {
var num: Int? // 根据num值抛出异常
func throwFunc() throws { // 如果有返回类型,throws需要写在(->)前面
guard num == 1 else { // 当num != 1 执行throw抛出异常
throw CustomErrorType.errorReason1 // 异常会传递到函数被调用的作用域
} // throw语句会立刻退出当前方法,相当于return
guard num == 2 else {
throw CustomErrorType.errorReason2
}
guard num == 3 else {
throw CustomErrorType.errorReason3
}
}
}
3、通过Do-Catch处理throwing函数传递的错误
let throwClass = ThrowClass()
throwClass.num = 4

do {
try throwClass.throwFunc()
}catch CustomErrorType.errorReason1 { // 根据返回错误类型,执行这个{}
print("errorReason1") // errorReason1
}catch CustomErrorType.errorReason2 {
print("errorReason2")
}catch { // catch没有指定类型,那么可以匹配任何错误
print("errorReason3")
}

你可能感兴趣的:(Swift学习笔记十四之错误处理)