我正在努力理解为什么我无法捕获NSJSONSerialization抛出的错误。
我期望捕获NSInvalidArgumentException
异常,但是应用程序却崩溃了。
这在使用Xcode 8的Swift 3和Swift 2.3中都发生了。
Swift 3:
do {
_ = try JSONSerialization.data(withJSONObject: ["bad input" : NSDate()])
}
catch {
print("this does not print")
}
Swift 2.3:
do {
_ = try NSJSONSerialization.dataWithJSONObject(["bad input" : NSDate()], options: NSJSONWritingOptions())
}
catch {
print("this does not print")
}
这段代码需要放在一个空的 Xcode 项目中 applicationDidFinishLaunching
方法中。在模拟器和设备上都经过测试。
完整异常信息:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
有什么想法,为什么catch块没有捕获到这个特定的错误?
NSDate
不是一个有效的 JSON 类型。修复编程错误。 - rmaddyisValidJSONObject
。 - Erik Villegastry
,因为dataWithJSONObject
被声明为throws
。不幸的是,文档非常模糊。关于“内部错误”的一些内容。但是使用isValidJSONObject
是你想要的,因为它将避免NSInvalidArgumentException
问题。无需桥接到Objective-C。 - rmaddy