如何在 Swift 中捕获算术溢出错误? [英] How does one trap arithmetic overflow errors in Swift?
问题描述
这个可能很容易.我们知道运算符 &+
对整数进行模运算(环绕),而运算符 +
会导致错误.
This one is probably easy. We know that the operator &+
does modular arithmetic on integers (wraps around), 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 kind of error is this? I can't catch it and I can't turn it in to 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.
我很确定这种错误与this Stack Overflow question中的错误相同(一个划分-by-zero) 但我不知道是否可以捕获这种错误.我错过了什么简单的事情?能不能被困?如果是,怎么办?
I'm pretty sure this kind of error is the same kind of error from this Stack Overflow question (a divide-by-zero) but I don't know if this kind of error can be trapped. What simple thing am I missing? Can it be trapped or not? If so, how?
推荐答案
区分异常和运行时错误.异常被抛出并且可以被捕获.运行时错误会使您的程序停止运行.添加和获取溢出是一个运行时错误,简单明了.没什么可抓的.
Distinguish between an exception and a runtime error. An exception is thrown and can be caught. A runtime error stops your program dead in its tracks. Adding and getting an overflow is a runtime error, plain and simple. There is nothing to catch.
像 &+
这样的操作符的重点是它不会出错,也不会告诉你有问题.这就是重点.
The point of an operator like &+
is that it doesn't error and it doesn't tell you there was a problem. That is the whole point.
如果您认为自己可能会溢出,并且想知道是否会溢出,请使用诸如 addWithOverflow
之类的静态方法.它返回一个由结果和一个 Bool 组成的元组,说明是否存在溢出.
If you think you might overflow, and you want to know whether you did, use static methods like addWithOverflow
. It returns a tuple consisting of the result and a Bool stating whether there was an overflow.
var x: Int8 = 100
let result = x &+ x // -56
x = 100
let result2 = Int8.addWithOverflow(x,x) // (-56, true)
这篇关于如何在 Swift 中捕获算术溢出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!