前言
从OC转Swift了。虽然Swift的官方语法的资料看了2遍了。还是在使用的时候遇到点问题。
好记性,不如烂笔头。本篇不是高深的内容。只是作为初使用的记录。当想给一个函数使用try-catch。需要在函数后加个throws
。具体使用,如下
enum ErrorType:Error{ case ErrorTypeNil case ErrorType1}
这里需要函数出错会抛出错误的情况,记住后面要加throws
。
func largerThanEighteenthFunc(a:Int16?) throws { if let need = a ,need >= 18{ print("need >>>> \(need)") throw ErrorType.ErrorTypeNil }else{ print("need <=18") throw ErrorType.ErrorType1 }}
不需要捕抓错误,可以使用try!或try?。但是不建议不建议使用try!,使用try?会更加安全。因为如果当有错误捕抓到时,程序会直接崩溃
func notPrintError() { try? largerThanEighteenthFunc(a: nil) }
如果只包含一个catch语句,那么所有的错误都会在这个catch中执行,能够捕抓其错误信息
func oneCondition() { do { try largerThanEighteenthFunc(a: 9) } catch let error { print("error >>> \(error)") } }
在使用catch时,我们想它是能够进行模式匹配的、能够进行更精准的错误匹配处理。可以穷举多种情况。
func twoCondition() { do { try largerThanEighteenthFunc(a: 20) } catch ErrorType.ErrorTypeNil { print(ErrorType.ErrorTypeNil) } catch ErrorType.ErrorType1 { print(ErrorType.ErrorType1) } catch { // 加入一个空的catch,用于关闭catch。否则会报错:Errors thrown from here are not handled because the enclosing catch is not exhaustive }}
注意:在使用do-catch的时候。无论是不是把错误都穷举完,一定要写个空catch,不然会报错。
这个错误就是Errors thrown from here are not handled because the enclosing catch is not exhaustive
友情连接: