Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My iOS app stops running after a run-time error occurs. I'm catching the error as an exception. I would like the app to continue running to the next steps after error handling. Any advises how to do this?

do {
    guard let ps: Element = try! docu.getElementById("product-name")! else { ide = "" }
    if ps != nil {
        ide = (try ps.text())
    }
} catch {
    print("error")
    ide = ""
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

I think you are overusing the ! (force unwrap) symbol here. It does not deal gracefully with nil values, in fact, it crashes.

I think what you might want to be doing here is

guard
    let ps: Element = try? doc.getElementById("product-name"),
    let ide = try? ps.text()
    else {
    print("error")
    ide = ""
}
// ide is guaranteed to be valid here
...

Note how if you use try? you do not need to "catch" the error, it will simply return an optional value, nil if the call would raise an exception.


Alternatively you could simply

let ps: Element = try? doc.getElementById("product-name")
let ide = try? ps?.text()
// ide will be an optional value here

If you really don't want to guard/if let...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...