问题
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.
回答1:
You can't do it in Swift.
Don't confuse errors and exceptions:
The idea of an error in Swift is to exit out of the current scope early.
The idea of an exception in Cocoa is that you are dead in the water; you should never have permitted this to happen.
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.
回答2:
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: {
})
来源:https://stackoverflow.com/questions/37494218/how-to-catch-nsunknownkeyexception-in-swift-2-2