I have a code where I want to set value for key as following:
item.setValue(field.1, forKey: field.0)
and I want to catch if the NSUnknownKeyException is thrown but I have the following code and it is not working:
do {
try item.setValue(field.1, forKey: field.0)
} catch _ {
print("Trying to set wrong value for the item ")
}
The displayed error when it is a not valid key is the following:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: setValue:forUndefinedKey:
How can I catch this exception?
Any help will be appreciated.
You can't do it in Swift.
Don't confuse errors and exceptions:
Now, it does happen that Cocoa sometimes throws an exception and catches it, itself. But such behavior is officially discouraged nowadays, and it is not something you can do in Swift. If the class you are sending this to is yours, you can implement setValue:forUndefinedKey:
as you please, but if an uncaught NSException happens that's the end of the game — and Swift cannot catch it.
You can catch the exception, using a Swift wrapper around Objective-C's @try/@catch
, such as https://github.com/williamFalcon/SwiftTryCatch.
Usage for your situation would be:
SwiftTryCatch.try({
item.setValue(field.1, forKey: field.0)
}, catch: { (exception) in
print("Trying to set wrong value for the item ")
}, finally: {
})