swift中异常处理try,throw学习小心得
try,throw 引入
错误处理是对程序中的错误条件进行响应和恢复的过程。Swift提供了在运行时抛出、捕获、传播和操作可恢复错误的一流支持。
Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.
[苹果官方文档][1]
[1]:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html
举例说明使用方式
一,简单的取值异常获取
创建user字典
// 创建字典
let user:[String:Any] = ["name":"yang", "age":20]
正常获取值
let name = user["name"] as! String
当字典中不存在key
let name = user["xiaoming"] as! String // 此时会报error
安全的取值方法
func getValueByKey(key:String){
guard let name = user[key] else {
print("取值失败")
return // throw
}
print(name)
}
getValueByKey(key: "name")
getValueByKey(key: "xiaoming")
打印的值
yang
取值失败
二,函数中的异常获取
枚举异常原因
enum UserError:Swift.Error{
case noKey(message:String) // key 无效
case ageBeyond // 年级超出
}
定义函数
func testAction() throws{
guard let name = user["name"] else {
print("取值失败")
throw UserError.noKey(message: "没有此人")
}
guard let value = user["age"] else {
throw UserError.noKey(message: "年龄无效")
}
let ageValue = value as! Int
guard ageValue > 100 else{
throw UserError.ageBeyond
}
}
函数调用,抛出异常
func getUser() throws {
do{
try testAction()
}catch let UserError.noKey(message){
print("error:\(message)")
}catch UserError.ageBeyond{
print("年龄不合适")
}catch{
print("other error")
}
}
使用函数
try getUser()
打印
年龄不合适
三, 写在最后
菜鸟一枚,望各位大佬指点.(一直在学习中....)