Swift 错误捕捉及处理⑪

2020-08-05  本文已影响0人  Aliv丶Zz

1. 自定义错误

enum SomeError : Error {
    case illegalArg(String)
    case outOfBounds(Int, Int)
    case outOfMemory
}

func divide(v1: Int, v2: Int) throws ->  Int {
    if v2 == 0 {
        throw SomeError.illegalArg("0不能作为除数")
    }
   return  v1 / v2
}


2. 处理Error

方式1

func test(){
    print("1")
    do{
        print("2")
        let res = try divide(v1: 10, v2: 0)
        print("res:",res)

    }catch  let SomeError.illegalArg(msg){
        print("参数异常:",msg)
    }catch  let SomeError.outOfBounds(size, index){
        print("下标越界:","size = \(size)","index = \(index)")
    }catch  let outOfMemory{
        print("内存溢出")
    }catch{
        print("其他错误")
    }
    print("4")
}

【打印结果】:

1
2
参数异常: 0不能作为除数
4

方式2

func test(){
    print("1")
    do{
        print("2")
        let res = try divide(v1: 10, v2: 0)
        print("res:",res)

    }catch let error{
        switch error {
            case let SomeError.illegalArg(msg):
                print("参数异常:",msg)
            default:
                print("11")
        }
    }
    print("4")
}

方式3,4

// 直接抛给上层
func test2() throws {
        let res = try divide(v1: 10, v2: 0)
        print("res:",res)
}
test2()
// 除SomeError错误类型外,其他抛给上层
func test3() throws {
    do{
        print("2")
        let res = try divide(v1: 10, v2: 0)
        print("res:",res)
    }catch is SomeError{
        print("SomeError")

    }
}

3 try? try!

var result1 = try? divide(v1: 20, v2: 2)//Optional(10) 
var result2 = try? divide(v1: 20, v2: 0)//nil 
var result3 = try! divide(v1: 20, v2: 2)//10
print(result1,result2,result3)//Optional(10) nil 10

4 rethrows

func exec(_ fn:(Int, Int) throws -> Int, _ num1: Int, _ num2: Int) rethrows {
    print(try fn(num1,num2))
}
//Fatal error: Error raised at top level:
try exec(divide, 20, 0)

5 defer

func processFile(){
    try divide(v1: 10, v2: 0)
    defer{
        print("defer")//即便divide报错,也会执行defer
    }
}
func fun1() {
    print("f1")
}
func fun2() {
    print("f2")
}
func testFn(){
    defer { fun1() }
    defer { fun2() }
}
testFn()

【打印结果】:

f2
f1

上一篇下一篇

猜你喜欢

热点阅读