How to print catch all exception information in Swift?

I am updating my code to use Swift, and I am wondering how to print error data for an exception that matches the catch all clause. I slightly modified the example of this page of the quick language guide to illustrate my point:

do { try vend(itemNamed: "Candy Bar") // Enjoy delicious snack } catch VendingMachineError.InvalidSelection { print("Invalid Selection.") } catch VendingMachineError.OutOfStock { print("Out of Stock.") } catch VendingMachineError.InsufficientFunds(let amountRequired) { print("Insufficient funds. Please insert an additional $\(amountRequired).") } catch { // HOW DO I PRINT OUT INFORMATION ABOUT THE ERROR HERE? } 

If I catch an unexpected exception, I need to be able to record something about what caused it.

+53
ios swift swift2
Jul 11 '15 at 1:37
source share
2 answers

I just figured it out. I noticed this line in the Swift Documentation:

If the catch clause does not specify a pattern, the clause will match and associate any error with a local constant named error

So, I tried this:

 do { try vend(itemNamed: "Candy Bar") ... } catch { print("Error info: \(error)") } 

And it gave me a good description.

+76
Jul 11 '15 at 1:43 on
source share

From Swift programming language :

If the catch clause does not specify a pattern, the clause will match and associate any error with a local constant named error .

That is, there is an implicit let error in the catch expression:

 do { // … } catch { print("caught: \(error)") } 

Alternatively, it seems that let constant_name also a valid pattern, so you can use it to rename the error constant (this can be convenient if the name error already in use):

 do { // … } catch let myError { print("caught: \(myError)") } 
+29
Jul 11 '15 at 1:44
source share



All Articles