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.
You use a do - catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it's matched against the catch clauses to determine which one of them can handle the error.
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 .
try – You must use this keyword in front of the method that throws. Think of it like this: “You're trying to execute the method. catch – If the throwing method fails and raises an error, the execution will fall into this catch block. This is where you'll write code display a graceful error message to the user.
According to Swift Error Handling Rationale, the general advice is: Logical error indicates that a programmer has made a mistake. It should be handled by fixing the code, not by recovering from it. Swift offers several APIs for this: assert() , precondition() and fatalError() .
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 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)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With