序言
對異常的正確處理能夠明確反映在代碼執(zhí)行中出現(xiàn)的問題弦疮,使得在接下來的debug快速定位問題所在的地方诱建,提高debug 效率钮蛛,同時也能對不同情況作出不同響應昂拂。
可以使用do-catch
和Assertions
處理異常情況受神,其中Assertions
主要還是用在程序發(fā)布前的debug階段。
do-catch
在此之前要先講講guard
格侯,顧名思義鼻听,就是守衛(wèi)的意思财著,用于判斷后面的條件是否成立,如果成立則往下執(zhí)行撑碴,如果不成立就執(zhí)行else
里面的代碼撑教,有點類似于單個的if
(guard
不能像if
一樣多個if-else
連接使用),有點不同的是guard后面的條件參數(shù)是可以被外部引用的醉拓,就像這樣:
func checkMessage(message:[String:String]) {
guard let name = message["name"] else{
NSLog("no name")
return
}
guard let ID = message["ID"] else{
NSLog("no ID")
return
}
NSLog("the name:\(name),the ID:\(ID)")
}
Swift在2.0中才引入了try
伟姐、catch
、do
亿卤、throw
愤兵、throws
、這五個關鍵字組成的異常處理機制怠噪,還有用到上面的guard
,下面用三明治的制作和品嘗過程為例來看看這幾個關鍵字的使用恐似。
假如這個三明治要有雞蛋,蔬菜傍念,香腸三種材料(假定面包片已經有了矫夷,哈哈),在制作過程中有可能出現(xiàn)三種材料不足的情況憋槐,用三種錯誤表示
enum MyError:ErrorType {
case NoEgg
case NoVegetable
case NoSausage
}
制作過程中如果發(fā)現(xiàn)材料不足就拋出異常双藕,
func makeASandwich(egg: Bool, vegetable: Bool, sausage: Bool) throws {
guard egg else{
throw MyError.NoEgg
}
guard vegetable else{
throw MyError.NoVegetable
}
guard sausage else{
throw MyError.NoSausage
}
}
接下來就可以真正開始制作了,在制作過程中拋出的異常要做一些特殊的處理阳仔,比如沒有雞蛋了忧陪,你就跟他說,哥們兒近范,你等等我這就給你買去...
func startMakingSandwich(egg: Bool, vegetable: Bool, sausage: Bool) {
do{
try makeASandwich(egg, vegetable: vegetable, sausage: sausage)
NSLog("eating sandwich")
}catch MyError.NoEgg {
NSLog("no egg")
}catch MyError.NoVegetable {
NSLog("no vegetable")
}catch MyError.NoSausage {
NSLog("no sausage")
}catch {
NSLog("ghostly presentce")
}
}
調用開始制作方法嘶摊,
startMakingSandwich(true, vegetable: true, sausage: false)
打印輸出信息:
2016-04-17 11:27:52.892 SwiftTest[57244:3967339] no sausage
Assertions
Assertions 用在deug階段,在某些值出現(xiàn)的不符合要求的情況下強制讓程序終止在這個位置评矩。
NOTE
Assertions cause your app to terminate and are not a substitute for designing your code in such a way that invalid conditions are unlikely to arise. Nonetheless, in situations where invalid conditions are possible, an assertion is an effective way to ensure that such conditions are highlighted and noticed during development, before your app is published.
它并不能避免某些特殊情況的發(fā)生叶堆,而只是在特殊情況發(fā)生時以高亮的形式表示,以引起開發(fā)者注意斥杜。
語法為:
assert(_:_:file:line:)
用法
func assertTest(someValue:Bool){
assert(someValue, "some strange error happen")
}
當someValue
為真時會繼續(xù)執(zhí)行下面的代碼虱颗,如果為假,則會拋出異常蔗喂,會讓程序終止在此處,同時打印出信息忘渔,其中文件路徑和異常代碼所在的行數(shù)編譯器會自動打出:
assertion failed: some strange error happen: file /Users/hah/Documents/Demo/testProject/SwiftTest/SwiftTest/ViewController.swift, line 187
NSExcetption
拋出異常機制
SnapKit中對于未添加到super view上就添加約束而導致的異常處理:
NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()