Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 697
ilovebigmacs Avatar asked Sep 19 '25 13:09

ilovebigmacs


1 Answers

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
}
like image 150
vadian Avatar answered Sep 21 '25 04:09

vadian