【问题标题】:swift - How to deal with uncaught exceptionswift - 如何处理未捕获的异常
【发布时间】:2015-09-10 13:15:03
【问题描述】:

如果使用NSSetUncaughtExceptionHandler,它只处理 Objective-C 运行时错误。 https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/index.html#//apple_ref/c/func/NSSetUncaughtExceptionHandler

NSSetUncaughtExceptionHandler 可以捕获异常:

var a: NSArray = [""]
println(a[2])

但是NSSetUncaughtExceptionHandler无法捕捉异常:

var a = [""]
println(a[2])

如何快速处理非目标 C 运行时错误(swift runtime errors)??

【问题讨论】:

  • 我有同样的问题,似乎 NSSetUncaughtExceptionHandler 不适用于 swift 异常。

标签: swift exception


【解决方案1】:

如果您希望处理索引外异常,那么您可以随时验证索引项

extension Collection {
    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    public subscript (safe index: Index) -> Element? {
      return indices.contains(index) ? self[index] : nil
    }
}

【讨论】:

    【解决方案2】:

    已经有一个详尽回答的类似问题Error-Handling in Swift-Language。查看那里的第一个答案,其中包括 Swift 2.0 中有关此主题的最新更新。

    【讨论】:

    • 我指的是未捕获的异常处理程序,而不是try catch
    • @Injoy - 你有解决办法吗
    • 这没有回答问题。链接的问题是关于用户级错误的,这个问题是关于捕获和处理致命错误的。我对该主题的研究表明,目前没有等效的方法来捕获致命错误。
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 2016-12-08
    • 2011-10-27
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    相关资源
    最近更新 更多