As one arithmetic error interrupt Swift?

It's probably easy. We know that the operator &+ performs modular arithmetic of integers (wrap), while the operator + causes an error.

 $ swift 1> var x: Int8 = 100 x: Int8 = 100 2> x &+ x $R0: Int8 = -56 3> x + x Execution interrupted. Enter Swift code to recover and continue. 

What is this error? I can not catch him, and I can not turn it into an optional:

  4> do {try x + x} catch {print("got it")} Execution interrupted. Enter Swift code to recover and continue. 5> try? x + x Execution interrupted. Enter Swift code to recover and continue. catch {print ( "got it")}  4> do {try x + x} catch {print("got it")} Execution interrupted. Enter Swift code to recover and continue. 5> try? x + x Execution interrupted. Enter Swift code to recover and continue. 

I'm pretty sure that this type of error - the same type of errors as in this matter Karoo (division by zero), but I do not know if we can intercept this type of error, What a simple thing I'm missing? This can be trapped or not? If so, how?

+7
source share
1 answer

Distinguish between exception and runtime error. An exception is thrown, and can be detected. Runtime error stops your program on their tracks. Adding and receiving overflow - a run-time error, plain and simple. Nothing to catch.

Type operator point &+ lies in the fact that it is not a fault and does not reflect a problem. That's the whole point.

If you think you can overflow, and want to know if you have made, use static methods such as addWithOverflow . It returns a tuple consisting of the result, and Bool, indicating the presence of an overflow.

 var x: Int8 = 100 let result = x &+ x // -56 x = 100 let result2 = Int8.addWithOverflow(x,x) // (-56, true) -56 var x: Int8 = 100 let result = x &+ x // -56 x = 100 let result2 = Int8.addWithOverflow(x,x) // (-56, true) 
+11
source

All Articles