swift 錯誤處理do catch try try!使用詳解
在swift中 如果我們要定義一個表示錯誤類型非常簡單,只要遵循Error協(xié)議就可以了,我們通常用枚舉或者結(jié)構(gòu)體來表示錯誤類型,枚舉可能用的多些,因為他能更直觀的表達(dá)當(dāng)前錯誤類型的每種錯誤細(xì)節(jié)。
//
// AboutError.swift
// learn_swiftUi
//
// Created by liuan on 2020/9/4.
// Copyright ? 2020 liuan. All rights reserved.
//
import Foundation
enum VendingMachingError:Error{
case invalideSelection
case insufficientFunds(coinsNeeded:Int)
case outOfStock
}函數(shù)、方法和初始化器都可以拋出錯誤。需要在參數(shù)列表后面,返回值加throws 關(guān)鍵字。
簡化版
func canThrowErrors() throws -> String
//
// AboutError.swift
// learn_swiftUi
//
// Created by liuan on 2020/9/4.
// Copyright ? 2020 liuan. All rights reserved.
//
import Foundation
enum VendingMachingError:Error{
case invalideSelection
case insufficientFunds(coinsNeeded:Int)
case outOfStock
}
struct Item {
var price: Int
var count: Int
}
class VendingMathine{
var inventory=[
"Candy bar":Item(price: 12, count: 7),
"Chips":Item(price: 10, count: 4),
"Pretzels":Item(price: 7, count: 11),
]
var coinsDeposited = 0
func vend(itemNaamed name:String) throws{
guard let item = inventory[name] else{
throw VendingMachingError.invalideSelection
}
guard item.count > 0 else{
throw VendingMachingError.outOfStock
}
guard item.price <= coinsDeposited else{
throw VendingMachingError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
}
coinsDeposited -= item.price
var newItem = item
newItem.count -= 1
inventory[name]=newItem
print("Dispensing \(name)")
}
}
let vm=VendingMathine()
vm.coinsDeposited=2
try vm.vend(itemNaamed: "Pretzels")拋出異常
Playground execution terminated: An error was thrown and was not caught:
? VendingMachingError
? insufficientFunds : 1 element
- coinsNeeded : 5在Swift中我們使用do-catch塊對錯誤進(jìn)行捕獲,當(dāng)我們在調(diào)用一個throws聲名的函數(shù)或方法時,我們必須把調(diào)用語句放在do語句塊中,同時do語句塊后面緊接著使用catch語句塊

do里面執(zhí)行調(diào)用語句
后面跟著catch 第一種錯誤 在第一種錯誤里面做處理
第二種錯誤需要符合一定的條件
然后做錯誤處理
第三種是沒有捕獲到的錯誤 然后在第三個語句里面做處理

如果你確信一個函數(shù)或者方法不會拋出錯誤,可以使用try! 來中斷錯誤的傳播,但是如果錯誤真的發(fā)生了。你會得到一個運(yùn)行時錯誤
// // AboutError.swift // learn_swiftUi // // Created by liuan on 2020/9/4. // Copyright ? 2020 liuan. All rights reserved. // import Foundation let photo = try! 5/0
warning: BlackMyPlayground.playground:10:19: warning: no calls to throwing functions occur within 'try' expression
let photo = try! 5/0
^
warning: BlackMyPlayground.playground:10:19: warning: no calls to throwing functions occur within 'try' expression
let photo = try! 5/0
^
error: BlackMyPlayground.playground:10:19: error: division by zero
let photo = try! 5/0
^defer關(guān)鍵字:defer block 例的代碼會在函數(shù)return之前執(zhí)行,無論函數(shù)是從哪個分之return的,還有throw,還是自然而然走到最后一樣。
//
// File.swift
// learn_swiftUi
//
// Created by liuan on 2020/9/4.
// Copyright ? 2020 liuan. All rights reserved.
//
import Foundation
func processFile(fileName: String)throws{
defer{
print("JIESHU")
}
print("KAISHI ")
}到此這篇關(guān)于swift 錯誤處理do catch try try!使用詳解的文章就介紹到這了,更多相關(guān)swift 錯誤處理do catch try try!內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Swift之for循環(huán)的基礎(chǔ)使用學(xué)習(xí)
這篇文章主要為大家介紹了Swift之for循環(huán)的基礎(chǔ)學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
Swift中Optional值的鏈?zhǔn)秸{(diào)用學(xué)習(xí)筆記
這篇文章主要介紹了Swift中Optional值的鏈?zhǔn)秸{(diào)用學(xué)習(xí)筆記,Optional鏈?zhǔn)荢wift入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2016-07-07
在 Swift 中測試 UIAlertController的方法
這篇文章主要介紹了在 Swift 中測試 UIAlertController的方法的,需要的朋友可以參考下2015-10-10
swift在IOS應(yīng)用圖標(biāo)上添加提醒個數(shù)的方法
本文是通過swift語言實現(xiàn)在應(yīng)用圖標(biāo)右上角添加消息個數(shù)提醒的功能,非常不錯,具有參考借鑒價值,感興趣的朋友一起看下吧2016-08-08

