2012年4月29日 星期日

[iOS] Exception catching

Exception catching is essential in developing application in .net framework and java.
While in Objective-C, it is much less powerful and shouldn't rely on it, as usually it just crash and didn't catch anything. Yet, it is still a plus if you really catch something.

Usage is really simple
@try
{
    Function_You_Want_To_Catch_Exception;
}
@catch (NSException* exception)
{
   Do_Thing_After_Exception_Caught;
}


One example is to put it in main.m, in order to catch any uncaught exception.
int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = -1;
    @try {
        retVal = UIApplicationMain(argc, argv, nil, nil);
    }
    @catch (NSException* exception) {
        NSLog(@"Uncaught exception: %@", exception.description);
        NSLog(@"Stack trace: %@", [exception callStackSymbols]);
    }
    [pool release];
    return retVal;
}
which shows how to catch all uncatched exception in the app.

Another usage is when you like "exception programming", you can raise your own exception, by using [NSException raise:format:] and catch it with above code.
Example:

[NSException raise:NSInvalidArgumentException format:@"Foo must not be nil"];

There are several exception name already defined by apple here. but if you want to use your own, put a NSString there is fine.

[iOS] Catch application end

Sometime we always want to catch the application terminate in mobile platform.

In iDevice, we can use
 - (void)applicationWillTerminate:(UIApplication *)application
to catch the terminate action.

But since iOS 4.0, application will goes to background instead of being killed when you press the home button.
If you are doing so,  
- (void)applicationWillTerminate:(UIApplication *)application 
might not be called.

From apple developer's guide,UIApplicationDelegate Protocol Reference 
- (void)applicationDidEnterBackground:(UIApplication *)application 
will be called instead.
 
When you goes to background, and kill the app bu double click the home button and click the red cross,
 - (void)applicationWillTerminate:(UIApplication *)application 

will still being called. But if it died naturally, then it won't be called.