swift force-unwrapping异常没有传播 [英] swift force-unwrapping exception not propagated
问题描述
我在swift中遇到了这种愚蠢的行为,强行解包一个可选项不会传播。
I've run into this silly behaviour in swift where force-unwrapping an optional does not propagate.
来自文档:
尝试使用!访问不存在的可选值会触发运行时错误。在使用之前,请务必确保可选项包含非零值!强制 - 展开其价值。
Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.
重现:
func foo(bar:String?) throws{
print(bar!);
}
和
try foo(nil);
这对我来说似乎不合逻辑或一致,我找不到有关此主题的任何文档。
This does not seem logical or consistent to me and I can't find any documentation on this subject.
这是设计的吗?
推荐答案
来自文档:
错误处理
错误处理是响应$ b $并从中恢复的过程b程序中的错误情况。 Swift提供了一流的支持
,用于在运行时抛出,捕获,传播和操纵可恢复的
错误。
Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.
...
代表和抛出错误
在Swift中,错误由符合的类型的值表示
ErrorType
协议。这个空协议表明一个类型可以
用于错误处理。
In Swift, errors are represented by values of types that conform to
the ErrorType
protocol. This empty protocol indicates that a type can
be used for error handling.
(注意: ErrorType
已在Swift 3中重命名为错误
(Note: ErrorType
has been renamed to Error
in Swift 3)
所以用 try / catch
你处理 Swift错误(符合 ErrorType $ c的类型的值$ c>协议)
throw
n。
这与运行时错误和运行时异常完全无关
(也与Foundation库中的 NSException
无关)。
So with try/catch
you handle Swift errors (values of types that conform to the ErrorType
protocol) which are throw
n.
This is completely unrelated to runtime errors and runtime exceptions
(and also unrelated to NSException
from the Foundation library).
请注意,关于错误处理的Swift文档甚至不使用
字异常,唯一例外(!)在(强调我的)中:
Note that the Swift documentation on error handling does not even use the word "exception", with the only exception (!) in (emphasis mine) in:
注意
NOTE
Swift中的错误处理类似于其他$ b中的异常处理 $ b语言,使用try,catch和throw关键字。与许多语言中的
异常处理不同 - 包括Objective-C-error
在Swift中处理不涉及展开调用堆栈,这可能是计算上昂贵的进程
。因此,抛出语句的性能
特征与
返回语句的性能相当。
Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.
nil
的期权的解包不会抛出
a
Swift错误(可以传播)和无法使用
尝试
。
The unwrapping of optionals which are nil
does not throw
a
Swift error (which could be propagated) and cannot be handled with
try
.
您必须使用众所周知的技术,例如
可选绑定,可选链接,检查 nil
等。
You have to use the well-known techniques like
optional binding, optional chaining, checking against nil
etc.
这篇关于swift force-unwrapping异常没有传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!