一、 do-catch & try
语法格式
do {
try //throw error语句
//没有错误发生时的后续语句
}catch {
//错误处理语句
}
举例子
//自定义错误类型枚举
enum ZZError: Error{
case err1
case err2
case err3
}
//有抛出错误的方法
func getNetwordData() throws {
throw ZZError.err1 //抛出错误
}
//调用函数
func myMethod() {
do{
try getNetwordData() //必须要有try
}catch let error{
print("error:\(error)")//捕捉到错误,处理错误
}
}
⚠️说明:
try 后面必须接用throws修饰的函数,当这个函数发送错误并throw error 时,由catch语句来捕捉并进行处理。
二、throws 关键字
可以抛出错误的方法必须在方法声明的后面加上 throws
关键字表示该方法可以抛出错误。
- 当方法没有返回值时,throws放在参数后面;
- 当方法有返回值时,throws放在参数和返回值之间;
func throwMethod1() throws{
}
func throwMethod2(_ parameter:Int8) throws ->(Bool){
}
网友评论