Exception catch in iOS use try...catch...finally.

Abnormal crahs situation, code example:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"0", @"1", nil];
    
// crash
[array removeObjectAtIndex:10];

When developing an APP, we usually need to catch exceptions, or handle exceptions to prevent them from suddenly crashing and giving users an unfriendly experience.
To prevent possible exceptions, you can use either assertions or simple if...else... judgments.

The sample code is as follows:

if (10 < array.count) {
	[array removeObjectAtIndex:10];
}
Another method of exception handling in Objective-C is similar to that in JAVA. The format is as follows:
@try {
    // code that may crash
} @catch (NSException *exception) {
    // caught exception exception

    // Throw an exception
    @throw exception
} @finally {
    // result processing
}

The sample code is as follows:

@try {
	NSLog(@"doing...");
	[array removeObjectAtIndex:10];
} @catch(NSException *exception) {
	NSLog(@"cathch error...");
	// @throw exception; Written will crash normally
	NSLog(@"exception = %@", exception);
} @finally {
	NSLog(@"finish...");
}

 or

@try {
	NSLog(@"doing...");
	[array removeObjectAtIndex:10];
} @finally {
	NSLog(@"finish...");
}
In addition, it is also possible to define and obtain exception information, and collect the obtained exception information for better analysis by developers.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);    
    return YES;
}

// Get exception crash information
void UncaughtExceptionHandler(NSException *exception) {
    NSArray *callStack = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSString *errorMessage = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
    NSLog(@"errorMessage = %@", errorMessage);
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325815446&siteId=291194637