1

How I can wrap in do catch overflow error

    let increasePerSecond: UInt32 = UInt32.max 
    let offset: UInt32
    do {
        offset = try ((nowTimeInterval - calculatedTimeInterval) * increasePerInterval)
    } catch _ {
        offset = 0
    }

But if I have error in do section I do not get in catch and have crash my app

UPD: It's not about how to get var offset, the question is how to handle the error ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
EvGeniy Ilyin
  • 1,817
  • 1
  • 21
  • 38
  • Have you tried explicitly casting `((nowTimeInterval - calculatedTimeInterval) * increasePerInterval)` as a UInt32? – Benjamin Lowry Feb 02 '17 at 12:54
  • it's not about how to get var offset, the question is how to handle the error – EvGeniy Ilyin Feb 02 '17 at 12:56
  • You should make your question more clear. It's really hard to understand what your actual problem is. For example, "handling the error" could be as simple has printing it out, so I doubt that's what you mean. – Benjamin Lowry Feb 02 '17 at 12:58

1 Answers1

2

Overflow in integer arithmetic does not throw an error, therefore you cannot catch it. If you want to detect and handle overflow, you can use one of the ...WithOverflow methods of the integer types. Example:

let a = UInt32.max
let b = UInt32(2)

if case let (result, overflow) = UInt32.multiplyWithOverflow(a, b), !overflow {
    print(result)
} else {
    print("overflow")
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382