【发布时间】:2017-10-07 06:40:45
【问题描述】:
我对@987654321@的理解是,当try?后面的表达式被求值时,如果有异常则返回nil,否则返回函数的返回值。
当我运行以下代码时:
guard let istream = InputStream(url: url),
let ambiguousObj = try? JSONSerialization.jsonObject(with: istream, options: []),
let jsonObj = ambiguousObj as? [[String: Any]] else {
throw ExportError.recoveredParseFailed
}
我收到与上面第二行有关的错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization JSONObjectWithStream:options:error:]: stream is not open for reading'
我了解如何修复错误。(我需要致电istream.open())
但是,有人可以帮我理解为什么 try? 在这种情况下没有捕捉到异常吗?
【问题讨论】:
-
你在
do { }catch{}块中添加了上面的代码吗? -
@BalajiGalave OP 使用的是
try?,而不是try,不需要 Do-Catch 块。 -
是的,我明白了。我们不需要它,而 try 是可选的
标签: ios swift error-handling optional