0

I started learning Swift yesterday coming from Python and Javascript (and VB.NET at school) and I have some trouble with the exception handling.

In Python I can just do this:

def myFunction(n):
    x = 3 / n
    return x

try:
    print(myFunction(0))
except Exception:
    print("Unexpected incident")

And it works as expected. Whereas in Swift I try to do the same:

func myFunction(n:Int) throws -> Float {
    var a:Float
    a = 3 / n
    return a
}
do {
    try print(myFunction(0))
} catch {
    print("Unexpected incident")
}

I realize this must be a very dumb question but I just can't get it. I read the answers from this question and one answer is about the do/try/catch syntax (third one) but I still do not see what I am doing wrong.

Any help would be appreciated.

Community
  • 1
  • 1
Nico
  • 194
  • 1
  • 12

1 Answers1

2

I don't think the division operator throws an exception in swift. You would have to manually throw the exception when n == 0

ie:

enum NumericalExceptions: ErrorType {
  case DivideByZero
}

func myFunction(n:Int) throws -> Float {
  guard n != 0 else {
    throw NumericalExceptions.DivideByZero
  }
  return 3 / Float(n)
}
do {
  try print(myFunction(0))
} catch {
  print("Unexpected incident")
}
ad121
  • 2,268
  • 1
  • 18
  • 24