swift force-unwrapping exception not propagated

前端 未结 2 2035
轮回少年
轮回少年 2020-12-01 21:07

I\'ve run into this silly behaviour in swift where force-unwrapping an optional does not propagate.

From the documentation:

Trying to use ! to

2条回答
  •  时光说笑
    2020-12-01 21:42

    this 'self explanatory' example can help you to see the difference between raising an runtime exception and throwing an error E conforming to ErrorType protocol.

    struct E: ErrorType{}
    func foo(bar:String?) throws {
        if let error = bar where error == "error" {
                throw E()
        }
        print(bar, "is valid parameter, but don't try to access bar.characters, it crash your code! (if bar == nil)")
        // here is everything OK 
        let bar = bar!
        // but here it crash!!
        _ = bar.characters
    }
    
    do {
        try foo("error")
        // next line is not accessible here ...
        try foo(nil)
    } catch {
        print("\"error\" as parameter of foo() throws an ERROR!")
    }
    do {
        try foo(nil) // fatal error: unexpectedly found nil while unwrapping an Optional value
    } catch {
    
    }
    

    it prints

    "error" as parameter of foo() throws an ERROR!
    nil is valid parameter, but don't try to access bar.characters, it crash your code! (if bar == nil)
    fatal error: unexpectedly found nil while unwrapping an Optional value
    

    raising an runtime exception is fatal error in your code.

提交回复
热议问题