How to print details of a 'catch all' exception in Swift? How to print details of a 'catch all' exception in Swift? ios ios

How to print details of a 'catch all' exception in Swift?


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

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

So, then I tried this:

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

And it gave me a nice description.


From The Swift Programming Language:

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

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

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

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

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