从非投掷方法中捕捉错误。

问题描述 投票:0回答:1

迅捷

Swift中的整数是可以的。它们不能像Doubles那样无限,以为。它们有一个极限。超过这个极限会导致崩溃。


证据A Int(10000000000000000000) error: integer literal '10000000000000000000' overflows when stored into 'Int'


附表B Int(pow(Double(1000000000), Double(10))) Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max


我天真地想:"嘿,这是一个致命的错误。我可以用做、抓块来抓到这个错误吗?" 不可以


证据C

do {
    Int(pow(Double(1000000000), Double(10)))
} catch {
    print("safety net")
}
print("good?")

warning: 'catch' block is unreachable because no errors are thrown in 'do' block Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max


哦,是的。是的,没错!我忘了加 尝试 不对


证据D

do {
    try Int(pow(Double(1000000000), Double(10)))
} catch {
    print("safety net")
}
print("good?")

warning: no calls to throwing functions occur within 'try' expression warning: 'catch' block is unreachable because no errors are thrown in 'do' block Fatal error: Double value cannot be converted to Int because the result would be greater than Int.max


这到底是怎么回事?

谁能给我解释一下?我真的很想能够 catch 这样的错误。非常感谢,这将是一个巨大的帮助!

swift int double try-catch fatal-error
1个回答
2
投票

你可以使用 init(exactly:) 构造函数,它不会抛出错误,但如果值过大,它将返回nil。

guard let value = Int(exactly: pow(Double(1000000000), Double(10))) else {
    //error handling
}
© www.soinside.com 2019 - 2024. All rights reserved.