With the new swift error handling introduced in 2.1 is it possible to specify a given ErrorType
a method will throw?
e.g.
class func nextOrderDate() throws OrderError -> NSDate {...}
It's called rethrows . The rethrows keyword is used for functions that don't directly throw an error.
Handling Errors Using Do-Catch. 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.
Where is the Reachability type defined? Maybe it has a throw -ing default initializer? The issue is that the initializer you are using is marked with 'throws' which means that it can throw an exception when it encounters a problem.
In Swift, instead of throwing a specific type, you catch specific types, like this:
do {
let date = try nextOrderDate()
} catch let error as OrderError {
print("OrderError")
} catch {
print("other error")
}
A workaround that I have seen many times, is to return the error instead (very often seen in completion blocks):
class func nextOrderDate() -> (NSDate?, OrderError?)
SWIFT 5
You can now use:
class func nextOrderDate() -> Result<NSDate, OrderError>
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