I am trying to understand why I cannot catch errors caused by NSJSONSerialization.
I expect the NSInvalidArgumentException
be raised and caught, but the application will NSInvalidArgumentException
instead.
This happens in both Swift 3 and Swift 2.3 using Xcode 8.
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") }
This code is placed in applicationDidFinishLaunching
inside an empty Xcode project. Tested both on the simulator and on the device.
Full exception:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
Any ideas why the catch block doesn't catch this particular error?
source share