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!!!



上一篇:MySQL 事务与锁机制


下一篇:SQL 存储过程入门(事务)