Is it possible to retrieve an exception inside a guard-statement with "try?"?
Asked Answered
L

2

33

In swift, is it possible to use the shorter guard let try? and get the occuring exception if entering the else block?

guard let smth = try? myThrowingFunc() else {
    print(error) //can I access the exception here somehow?
    return
}

vs

let smth: AnyObject?
do {
    smth = try myThrowingFunc()
} catch let error {
    print(error)
    return
}
Lyre answered 3/3, 2016 at 15:33 Comment(4)
I'm pretty sure that try? is like as? and will just turn smh into an optional enum where you're left to unwrap / validate it as required. meaning, I think it takes out of the do/catch paradigmBaillargeon
Yes, and 'guard let smth = ...' tries to unwrap - if it fails, then it will execute the else block. So this construct could be wonderful, if it would be possible to somehow access the exception ...Lyre
But thanks, I could understand how it works and answer my question myself!Lyre
Any update on this? Has this been addressed?Anhydrous
L
28

I have found page no 42 in "The Swift Programming Language (Swift 2.2 Prerelease)" where it states explicitly the following:

Another way to handle errors is to use try? to convert the result to an optional. If the function throws an error, the specific error is discarded and the result is nil. Otherwise, the result is an optional containing the value that the function returned.

So, this would rather be a feature request for apple then. As a matter of fact there's already some discussion on this topic here:

http://thread.gmane.org/gmane.comp.lang.swift.evolution/8266

Lyre answered 3/3, 2016 at 16:19 Comment(2)
I use this pattern, if let some = try someOptional { } often where I don't need to worry about catching stuff.Baillargeon
Yes, its the opposite of the guard thing. The guard is very useful for early-exiting a function. I have registered for the swift-evolution mailing list, and there seems to be interest in that feature, because already someone else had the same idea: thread.gmane.org/gmane.comp.lang.swift.evolution/8266Lyre
S
2

Unfortunately, we can't.

I found Chris Lattner's own response to this question in this discussion.

This is inconsistent with what we currently have, because “if let” and “guard let” match against an optional and succeed iff the optional is present. You were seemingly saying that the presence of “catch” later in the statement would affect this very primitive behavior that we have. I’m not a strong believer in this proposal, because it is adding complexity and sugar, but I haven’t seen strong motivation that it is common. This isn’t to say that it isn’t common and worthwhile, just that I haven’t seen any evidence.

Stalactite answered 23/2, 2023 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.