I get how I can create my own errors and trigger them in Swift with the throws
keyword. What I don't get is how to replicate the regular try - catch
found in other languages (or the Ruby rescue
) for unhandled exceptions.
Example (In Swift):
func divideStuff(a: Int, by: Int) -> Int {
return a / by
}
let num = divideStuff(4, by: 0) //divide by 0 exception
Here's how I'd deal with it in C#, for example:
int DivideStuff(int a, int b) {
int result;
try {
result = a / b;
}
catch {
result = 0;
}
return result;
}
How can I achieve the same with Swift?