作為一位ios開發(fā)一般都很少用到try catch,因為一般不小心可能會造成一些內(nèi)存泄露,先來看個例子
先創(chuàng)建幾個測試類
TestExceptions.h
#import <Foundation/Foundation.h>
@interface TestExceptions : NSObject
@end
TestExceptions.m
#import "TestExceptions.h"
@implementation TestExceptions
- (void)dealloc {
NSLog(@"TestExceptions---dealloc");
}
@end
先看看非ARC環(huán)境下
ViewController.m
@try {
TestExceptions * exception = [[TestExceptions alloc] init];
//主動異常
@throw [[NSException alloc] initWithName:@"主動異常" reason:@"這是錯誤原因" userInfo:nil];
[exception release];
}
@catch (NSException *e) {
NSLog(@"%@",e);
}
咋一看可能沒什么問題,但仔細一看會發(fā)現(xiàn)TestExceptions對象并沒有釋放,因為@throw [[NSException alloc] initWithName:@"主動異常" reason:@"這是錯誤原因" userInfo:nil];中斷了[exception release];執(zhí)行導致不能正常釋放,當然你可能會像下面這樣修改代碼
TestExceptions * exception = nil;
@try {
exception = [[TestExceptions alloc] init];
@throw [[NSException alloc] initWithName:@"主動異常" reason:@"這是錯誤原因" userInfo:nil];
}
@catch (NSException *e) {
NSLog(@"%@",e);
}
@finally {
[exception release];
}
這樣確實是釋放了,但是由于@finally會用到exception對象所以還要放到外面,如果try里面有很多對象的時候會很繁瑣
再來看看ARC下
@try {
TestExceptions * exceptionption = [[TestExceptions alloc] init];
@throw [[NSException alloc] initWithName:@"主動異常" reason:@"這是錯誤原因" userInfo:nil];
}
@catch (NSException *e) {
NSLog(@"%@",e);
}
由于arc下沒有release方法,導致對象更加沒法釋放了,本以為arc會自動處理這種情況,然而事實并沒有,我們可以手動將ViewController.m文件改為-fobjc-arc-exceptions則會出處理該種情況

15231751172151.jpg
輸出
TestExceptions---dealloc
還有一種當文件處于objective-c++模式的時候也就是.mm格式時,arc會默認打開-fobjc-arc-exceptions,所以我們也可以像下面這樣修改
修改ViewController.m為ViewController.mm發(fā)現(xiàn)也是正常釋放了
可以發(fā)現(xiàn)
使用try catch還是有不少問題的,所以蘋果推薦使用NSError模式處理異常,再改造一下
- (void)viewDidLoad {
[super viewDidLoad];
NSError *err = nil;
[self testTemoExcep:&err];
if (err) {
NSLog(@"%@",err);
}
}
- (void)testTemoExcep:(NSError **)error {
TestExceptions * exceptionption = [[TestExceptions alloc] init];
*error = [NSError errorWithDomain:@"異常" code:500 userInfo:nil];
}