Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 640
Jiho Kang Avatar asked Aug 16 '13 09:08

Jiho Kang


1 Answers

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.

like image 87
Mike Weller Avatar answered Nov 15 '22 07:11

Mike Weller