ilovebigmacs ilovebigmacs - 5 months ago 28
Swift Question

How to use try-catch in Swift?

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?

Answer

In Swift there is no functionality to catch arbitrary runtime errors.
The developer is responsible to handle the errors properly.

For example

func divideStuff(a : Int, b : Int) -> Int {
  if b == 0 { return 0 }
  return a / b
}