Is it safe to catch an exception from [NSObject removeObserver:forKeyPath:]?

cocoa, ios, key-value-observing, nsnotificationcenter, objective-c

Solution

Exceptions, especially from internal Apple APIs, should never be silently caught and ignored. In Objective-C an exception should generally cause your app to terminate, unlike other languages and runtimes (Java, .NET) where catching exceptions is a normal part of development.

If you are getting a crash, you have a bug somewhere and you need to fix it. Swallowing an exception could have pretty bad consequences due to getting into an inconsistent state. Don't do it.

Problem

I have some code that uses KVO heavily and have addObserver:forKeyPath: and removeObserver:forKeyPath: in multiple places. The app will occasionally crash with "cannot remove observer for key path." I was wondering if it would be safe to just try/catch the exception to prevent the app from crashing. I know it's not the best approach in handling KVO but I need to buy some time before I can clean up the code.

Original source

Related problems