3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Miguelme
  • 609
  • 1
  • 6
  • 17
  • 1
    It is not a catchable error. It is an exception! Compare the discussion here http://stackoverflow.com/questions/35973899/how-does-one-trap-arithmetic-overflow-errors-in-swift – matt May 28 '16 at 03:52
  • @matt As in other languages aren't exceptions catchable ? – Miguelme May 28 '16 at 13:14
  • Objective-C exceptions indicate programming errors. You don't catch programming errors. You fix them. – gnasher729 May 28 '16 at 22:06
  • Does this answer your question? [Catching NSException in Swift](https://stackoverflow.com/questions/32758811/catching-nsexception-in-swift) – Sindre Sorhus Mar 09 '20 at 14:46

2 Answers2

4

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.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • If you don't like how this works, and you don't want to use Objective-C, you might like to file an enhancement request with Apple — though to be honest I've no idea whether catching an Objective-C exception in Swift would be possible even if they _wanted_ to allow it. – matt May 28 '16 at 18:30
  • Exception = dead in the water. Have to remember that one :-) – gnasher729 May 28 '16 at 22:07
0

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: {

})
Ric Santos
  • 15,419
  • 6
  • 50
  • 75