swift中異常處理try,throw學(xué)習(xí)小心得
try,throw 引入
錯(cuò)誤處理是對程序中的錯(cuò)誤條件進(jìn)行響應(yīng)和恢復(fù)的過程。Swift提供了在運(yùn)行時(shí)拋出、捕獲、傳播和操作可恢復(fù)錯(cuò)誤的一流支持。
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
舉例說明使用方式
一,簡單的取值異常獲取
創(chuàng)建user字典
// 創(chuàng)建字典
let user:[String:Any] = ["name":"yang", "age":20]
正常獲取值
let name = user["name"] as! String
當(dāng)字典中不存在key
let name = user["xiaoming"] as! String // 此時(shí)會報(bào)error
安全的取值方法
func getValueByKey(key:String){
guard let name = user[key] else {
print("取值失敗")
return // throw
}
print(name)
}
getValueByKey(key: "name")
getValueByKey(key: "xiaoming")
打印的值
yang
取值失敗
二,函數(shù)中的異常獲取
枚舉異常原因
enum UserError:Swift.Error{
case noKey(message:String) // key 無效
case ageBeyond // 年級超出
}
定義函數(shù)
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
}
}
函數(shù)調(diào)用,拋出異常
func getUser() throws {
do{
try testAction()
}catch let UserError.noKey(message){
print("error:\(message)")
}catch UserError.ageBeyond{
print("年齡不合適")
}catch{
print("other error")
}
}
使用函數(shù)
try getUser()
打印
年齡不合適
三, 寫在最后
菜鳥一枚,望各位大佬指點(diǎn).(一直在學(xué)習(xí)中....)