ilovebigmacs
ilovebigmacs

Reputation: 993

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?

Upvotes: 4

Views: 5885

Answers (2)

Viktor Simkó
Viktor Simkó

Reputation: 2637

You can also handle it like this:

enum MyErrors: ErrorType {
  case DivisionByZero
}

func divideStuff(a: Int, by: Int) throws -> Int {
  if by == 0 {
    throw MyErrors.DivisionByZero
  }
  return a / by
}

let result: Int

do {
  result = try divideStuff(10, by: 0)
} catch {
  // ...
}

Upvotes: 2

vadian
vadian

Reputation: 285072

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
}

Upvotes: 2

Related Questions