錯誤類型
1伐谈、開發(fā)過程常見的錯誤
語法錯誤(編譯報錯)
邏輯錯誤
運(yùn)行時錯誤(可能會導(dǎo)致閃退,一般也叫做異常)试疙,也是我們今天講的重點
自定義錯誤
1诵棵、Swift中可以通過Error協(xié)議自定義運(yùn)行時的錯誤信息
enum SomeError: Error {
case illegalArg(String)
case outOfBounds(Int, Int)
case outOfMemory
}
2、函數(shù)內(nèi)部通過throw拋出自定義Error祝旷,可能會拋出Error的函數(shù)必須加上throws聲明
func divide(_ num1: Int, _ num2: Int) throws -> Int {
if num2 == 0 {
throw SomeError.illegalArg("0不能作為除數(shù)")
}
return num1 / num2
}
3履澳、需要使用try調(diào)用可能會拋出Error的函數(shù)
4、可以使用do-catch捕捉Error
func test() {
do {
try divide(20, 0)
} catch let SomeError.illegalArg(msg) {
print("參數(shù)異常:", msg)
} catch let SomeError.outOfBounds(size, index) {
print("下標(biāo)越界:", "size = \(size), index = \(index)")
} catch SomeError.outOfMemory {
print("內(nèi)存溢出")
} catch {
print("其他錯誤")
}
}
5怀跛、拋出Error后距贷,try下一句直到作用域結(jié)束的代碼都停止運(yùn)行
處理Error
1、處理Error的2種方式
a吻谋、通過do-catch捕捉Error
b忠蝗、不捕捉Error,在當(dāng)前函數(shù)增加throws聲明滨溉,Error將自動拋給上層函數(shù)
func test() throws {
print(try divide(200, 0))
}
如果最頂層函數(shù)(main函數(shù))依然沒有捕捉Error什湘,那么程序?qū)⒔K止
以下是幾種error的處理方法:
func test() throws {
do {
print(try divide(200, 0))
} catch let error as SomeError {
print(error)
}
}
func test() throws {
do {
print(try divide(200, 0))
} catch is SomeError {
print("SomeError")
}
}
do {
try divide(20, 0)
} catch let error {
switch error {
case let SomeError.illegalArg(msg):
print("參數(shù)異常:", msg)
default:
print("其他異常")
}
}
我們通過一個例子來總結(jié)一下處理Error的2種方式:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
try test0()
}
func test0() throws -> Void {
try test1()
}
func test1() throws -> Void {
try test2()
}
func test2() throws -> Void {
do {
print(try divide(200, 0))
} catch is SomeError {
print("This is SomeError")
}
}
try?、try!
1晦攒、可以使用try?闽撤、try!調(diào)用可能會拋出Error的函數(shù),這樣就不用去處理Error
func test() -> Void {
print("1")
var result1 = try? divide(20, 10) // Optional(2), Int?
var result2 = try? divide(20, 0) // nil
var result3 = try! divide(20, 10) // 2, Int
print("2")
}
2脯颜、a哟旗、b是等價的
var a = try? divide(20, 0)
var b: Int?
do {
b = try divide(20, 0)
} catch {
b = nil
}
rethrows
1、rethrows表明:函數(shù)本身不會拋出錯誤栋操,但調(diào)用閉包參數(shù)拋出錯誤闸餐,那么它會將錯誤向上拋
func exec(_ fn: (Int, Int) throws -> Int, _ num1: Int, _ num2: Int) rethrows -> Void {
print(try fn(num1, num2))
}
defer
1、defer語句:用來定義以任何方式(拋錯誤矾芙、return等)離開代碼塊前必須要執(zhí)行的代碼
defer語句將延遲到當(dāng)前作用域結(jié)束之前執(zhí)行
func open(_ filename: String) -> Int {
print("open")
return 1
}
func close(_ file: Int) -> Void {
print("close")
}
func processFile(_ filename: String) throws -> Void {
let file = open(filename)
defer {
close(file)
}
try divide(20, 0)
}
2舍沙、defer語句的執(zhí)行順序與定義順序相反
func fn1() -> Void {
print("fn1")
}
func fn2() -> Void {
print("fn2")
}
func testDefer() -> Void {
defer {
fn1()
}
defer {
fn2()
}
} //fn2 fn1