Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 } 
like image 961
smat88dd Avatar asked Mar 03 '16 15:03

smat88dd


People also ask

Do try catch exception Swift?

The try/catch syntax was added in Swift 2.0 to make exception handling clearer and safer. It's made up of three parts: do starts a block of code that might fail, catch is where execution gets transferred if any errors occur, and any function calls that might fail need to be called using try .

What is guard in Swift?

In Swift, we use the guard statement to transfer program control out of scope when certain conditions are not met. The guard statement is similar to the if statement with one major difference. The if statement runs when a certain condition is met. However, the guard statement runs when a certain condition is not met.


1 Answers

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

like image 72
smat88dd Avatar answered Oct 12 '22 03:10

smat88dd