閱讀655 返回首頁    go 阿裏雲 go 技術社區[雲棲]


obj-c編程07:異常處理

    好了,到了相對輕鬆的話題,也是所有語言無可避免的話題:異常的處理。

    我們知道對於一些常見的語言,“異常”是逃不開避不掉的主題:C中相對原始的signal或依賴係統異常支持(比如windows),C++和C#以及java中完善的內置語法,還有ruby中靈活的動態方式,在這裏我們看到的是和java類似的obj-c的方法:

#import <Foundation/Foundation.h>

int main(int argc,char *argv[])
{
	@autoreleasepool{
		NSLog(@"hello obj-c!");

		int i = 0,j = 100;

		@try{
			i = j / i;
			NSLog(@"Do you see me???");
		}
		@catch(NSException *e){
			NSLog(@"caught %@:%@",[e name],[e reason]);
		}
	}
	return 0;
}

我們還可以用@throw拋出自己的異常:

#import <Foundation/Foundation.h>

@interface MyError:NSException
@end

@implementation MyError
	-(NSString*)name{
		return @"My ERROR!NEVER!";
}
	-(NSString*)reason{
		return @"NO REASON!";
	}
@end

int main(int argc,char *argv[])
{
	@autoreleasepool{
		NSLog(@"hello obj-c!");

		MyError *mye = [[MyError alloc] init];

		int i = 0,j = 100;

		@try{
			@throw mye;
			i = j / i;
			NSLog(@"Do you see me???");
		}
		@catch(NSException *e){
			NSLog(@"caught %@:%@",[e name],[e reason]);
		}
	}
	return 0;
}

apple@kissAir: objc_src$./3

2014-06-30 11:05:40.389 3[1280:507] hello obj-c!

2014-06-30 11:05:40.391 3[1280:507] *** Terminating app due to uncaught exception of class 'nil'

libc++abi.dylib: terminating with uncaught exception of type nil

Abort trap: 6


呀!執行咋錯了呢?隻能用NSException類嗎?原因不明啊:

#import <Foundation/Foundation.h>

@interface MyError:NSException
@end

@implementation MyError
	-(NSString*)name{
		return @"My ERROR!NEVER!";
}
	-(NSString*)reason{
		return @"NO REASON!";
	}
@end

int main(int argc,char *argv[])
{
	@autoreleasepool{
		NSLog(@"hello obj-c!");

		//MyError *mye = [[MyError alloc] init];

		int i = 0,j = 100;

		@try{
			@throw [NSException exceptionWithName: @"MyERROR" \
				reason: @"NoREASON!" userInfo: nil]3;
			i = j / i;
			NSLog(@"Do you see me???");
		}
		@catch(NSException *e){
			NSLog(@"caught %@:%@",[e name],[e reason]);
		}
	}
	return 0;
}

最後介紹一下@finally的語法,@finally類似於java中的finally或者ruby中的ensure語句,表示無論發生啥都必須執行的代碼,常常用在確保資源釋放的場所:

int main(int argc,char *argv[])
{
	@autoreleasepool{
		NSLog(@"hello obj-c!");

		//MyError *mye = [[MyError alloc] init];

		int i = 0,j = 100;

		@try{
			@throw [NSException exceptionWithName: @"MyERROR" \
				reason: @"NoREASON!" userInfo: nil];
			i = j / i;
			NSLog(@"Do you see me???");
		}
		@catch(NSException *e){
			NSLog(@"caught %@:%@",[e name],[e reason]);
		}
		@finally{
			NSLog(@"in finally,you must see me!!!");
		}
	}
	return 0;
}

apple@kissAir: objc_src$clang -fobjc-arc -framework Foundation 3.m -o 3

apple@kissAir: objc_src$./3

2014-06-30 11:09:34.263 3[1304:507] hello obj-c!

2014-06-30 11:09:34.265 3[1304:507] caught MyERROR:NoREASON!

2014-06-30 11:09:34.265 3[1304:507] in finally,you must see me!!!



最後更新:2017-04-03 06:03:10

  上一篇:go sql 查詢所有數據庫、表名、表字段總結
  下一篇:go Cortex-M3