Tony Friz Tony Friz - 1 year ago 119
Objective-C Question

@try@catch block not catching inside exception

OK, I've never seen this before. Here is my code:

@try {
[self.avPlayer removeObserver:self forKeyPath:@"status"];
[self.avPlayer removeObserver:self forKeyPath:@"rate"];
} @catch (NSException *exception) {

} @finally {


You can quite clearly see, I have those 2 lines of code in the @try block. However, it's still crashing my app. Here's the uncaught exception message:

Cannot remove an observer <SoulHLECellView 0x7fa8d2b536b0> for the key path "status" from <AVPlayer 0x7fa8d714ad70> because it is not registered as an observer.

So, very clearly, this is being caused by the code I've posted above. How the heck is this possible? What am I missing here?

Answer Source

To answer your question as to why you aren't actually catching the exception, there are certain types of exceptions that cannot be caught; see for a pretty good explanation of what these are, what their causes are, and what to do about them. I suspect that the exception that's actually getting thrown is a runtime exception that you can't actually handle with @try/@catch.

To triage, you can try setting a breakpoint on -[NSException raise] in CoreFoundation or objc_exception_throw in libobjc.A.dylib, and more than likely that breakpoint will capture what the actual exception is and give you a clue as to why you aren't catching it.

All that being said, @gnasher729 hit the nail on the head as to how best to handle this type of situation in the long run (i.e. code that you want to actually release out into the world).