从非抛出方法捕获错误

Catching an error from a non-throwing method

Swift

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


我天真地想,“嘿,这是一个致命错误。我可以用 do, catch 块捕获错误吗?”
没有


图表 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


哦,是的。那就对了!我忘了添加 try
没有


图表 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 这样的错误。
非常感谢,这将是一个巨大的帮助!

您可以使用 init(exactly:) 构造函数,它不会抛出错误,但如果值太大,它会 return nil

guard let value = Int(exactly: pow(Double(1000000000), Double(10))) else {
    //error handling
}