How to print details of a 'catch all' exception in Swift?
I'm updating my code to use Swift, and I'm wondering how to print error details for an exception that matches the 'catch all' clause. I've slightly modified the example from this Swift Language Guide Page 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 log something about what caused it.
Solution 1:
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.
Solution 2:
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 namederror
.
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)")
}