【问题标题】:try? propagates rather than returning nil尝试?传播而不是返回 nil
【发布时间】:2017-10-07 06:40:45
【问题描述】:

我对@9​​87654321@的理解是,当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


【解决方案1】:

try? 计算表达式并在抛出 Swift error 时返回 nil 在评估过程中。在您的情况下,基金会图书馆抛出 一个Objective-C NSException,如果你设置了异常断点就可以看到:

(lldb) BT * 线程 #1,队列 = 'com.apple.main-thread',停止原因 = 断点 1.1 帧#0:0x00007fffbe5cb45d libobjc.A.dylib`objc_exception_throw 帧 #1: 0x00007fffa9855c3d CoreFoundation`+[NSException raise:format:] + 205 帧 #2:0x00007fffab3a001a 基础`+[NSJSONSerialization JSONObjectWithStream:options:error:] + 178

Objective-C 异常不能在 Swift 中被捕获(除非你 使用 Objective-C 包装器,例如参见 Catching NSException in Swift)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多