swift - 如何处理未捕获的异常

标签 swift exception

如果使用 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])

How swift deal with non-objective-C runtime errors(swift runtime errors)??

最佳答案

如果您希望处理超出索引的异常,那么您始终可以验证索引项

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
    }
}

关于swift - 如何处理未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31024803/

相关文章:

android - 媒体播放器异常

ios - 如何在 swift 3 开始编辑时为多个 uitextfield 设置边框颜色?

ios - 在 Firestore for Swift 中按时间戳传递和过滤项目

ios - SwiftUI View 无法正确呈现为UIImage

python - 如何排除 SyntaxError?

C++ 异常规范 - 处理无效异常

ios - iOS 中的简单计时器

ios - 如何快速比较颜色

c++ - 在 Paint() 中时出现 SEHException - .NET 处理正在破坏调用堆栈

Java 类未找到异常