一、异常的捕获
和java类似,使用:
@try{
}
@catch{
}
@finally{
}
示例代码
@try {
NSArray *array = [NSMutableArray array];
// 从空数组里面取值(有异常)
[array objectAtIndex:0];
}
@catch (NSException *exception) {
NSLog(@"异常:%@", exception.name);
NSLog(@"原因:%@", exception.reason);
}
@finally {
NSLog(@"finally");
}
二、异常抛出
1)使用@throw
在有异常的地方直接使用@throw 可以将异常抛到上一层。 也可以使用“ @throw + 异常 ” 抛出指定的异常
示例代码:
/** 通过@throw抛出异常*/
@try {
// 抛出一个字符串异常
@throw @"string exception";
}
@catch (NSString *exception) {
// 捕捉字符串异常
NSLog(@"%@", exception);
}@catch (id exception) {
// 捕捉其他异常
NSLog(@"%@", exception);
// 将异常抛到上一层
@throw;
}
2)使用raise:format:
调用方法:
+ (void)raise:(NSString *)name format:(NSString *)format, ...
name:异常名称 format:异常原因
示例代码:
/** raise方式抛出异常 */
@try {
[NSException raise:@"TestException" format:@"测试"];
}
@catch (NSException *exception) {
NSLog(@"异常:%@", exception.name);
NSLog(@"原因:%@", exception.reason);
}
参考文章:http://www.objectivec-iphone.com/introduction/exception/throw-raise.html