swift中異常處理try,throw學(xué)習(xí)小心得

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í)中....)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容