4

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?

ilovebigmacs
  • 983
  • 16
  • 28
  • It's `do`.. `catch` in the doc: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html – Jonas Jun 15 '16 at 12:10
  • 1
    You *cannot* catch arbitrary runtime exceptions (such as division by zero) with try/catch, compare http://stackoverflow.com/questions/34628999/swift-force-unwrapping-exception-not-propagated for a similar question and links to the documentation. – Martin R Jun 15 '16 at 12:11

2 Answers2

2

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
}
vadian
  • 274,689
  • 30
  • 353
  • 361
2

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 {
  // ...
}
Viktor Simkó
  • 2,607
  • 16
  • 22
  • You may want to add a catch let error as NSError to the do/catch statement so that the error can be identified in the catch portion – Ike10 Jun 15 '16 at 15:05