问题
I have simple code that executes and in case it crashes I want to catch the exception so the app does not crash.
@try {
x = [self try_doMyWork:Param];
} @catch (NSException* e) {
NSLog(@"Exception");
}
While this code works in debug and catches the exception (which is a simple index beyond end of array) it crashes in distributed apps on iPhones.
Why is this and how can I ensure that it also works on distributed apps?
回答1:
Uncaught application-level exceptions are only one cause of crashes. BSD signals, like EXC_BAD_ACCESS, can also cause crashes - and catching NSExceptions won't prevent those.
It's impossible to say what the specific crash is without knowing the details of try_doMyWork:, but I think the most common cause of crashes in the C layer (not the Objective-C layer) is memory management problems - an attempt at writing or reading something your app is not supposed to access. The most likely explanation is that the exception you see in debug is not the same as the error you see in distribution.
回答2:
In debug mode, the heap manager may allocate objects with buffer zones before and after them (called guards) and fill those guards with known values (like 0x7F). It does this so that it can test those guards when you release the memory and it can tell if you wrote beyond the end of the allocated memory (or before the start of it). In this way it can advise you that your code has a bug (a memory scribbler).
In release mode, it does not create these guards and so when you write outside of the allocated memory, bad things (like crashes) happen.
来源:https://stackoverflow.com/questions/15714255/why-does-this-code-crash-on-the-distributed-app-but-work-in-the-debugger