这个可能很简单。我们知道运算符 &+
对整数进行模运算(环绕),而运算符 +
会导致错误。
$ 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.
这是什么错误?我无法捕捉到它,也无法将它变成可选的:
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.
我很确定这种错误与 this Stack Overflow question 中的错误类型相同(一个被零除)但是我不知道这种错误是否可以被捕获。我错过了什么简单的事情?能不能困住?如果是,怎么办?
最佳答案
区分异常和运行时错误。异常被抛出并且可以被捕获。运行时错误会使您的程序停止运行。添加和获取溢出是一个运行时错误,简单明了。没有什么可抓的。
像 &+
这样的运算符的要点是它不会出错,也不会告诉你有问题。这就是重点。
如果您认为自己可能会溢出,并且想知道自己是否溢出了,请使用 addWithOverflow
等静态方法。它返回一个由结果和一个 Bool 组成的元组,该 Bool 表明是否存在溢出。
var x: Int8 = 100
let result = x &+ x // -56
x = 100
let result2 = Int8.addWithOverflow(x,x) // (-56, true)
关于swift - 如何在 Swift 中捕获算术溢出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973899/