标签:
在开发过程中,经常要用到异常处理,防止 程序突然崩溃,在java,c++ 中有抛异常,和断言处理,那么在oc中 是怎么处理异常的呢?
1. NSAssert
看看ios 是怎么定义
#if !defined(_NSAssertBody) #define NSAssert(condition, desc, ...) do { __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS if (!(condition)) { [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd object:self file:[NSString stringWithUTF8String:__FILE__] lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; } __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS } while(0) #endif
具体用法:
如果condition 为假,就抛出异常
int a = 0; NSAssert(a!=0,@"x must not be zero", __func__);
抛出的异常信息:
2015-11-21 19:58:47.692 AudioDemo[1928:60b] *** Assertion failure in -[GNViewController touchesBegan:withEvent:], /Users/geng/Desktop/programe/音频/AudioDemo/AudioDemo/GNViewController.m:41
2. 由于NSAssert 引用了self,所以,在block时候,会容易引起循环引用,所以一般用下面的断言
#define NSCAssert(condition, desc, ...) do { __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS if (!(condition)) { [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] file:[NSString stringWithUTF8String:__FILE__] lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; } __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS } while(0)
3.throw 抛异常
// 抛出异常 if (num > 10 ) { NSException* exp = [NSException exceptionWithName:@"num > 10" reason:@"num > 10" userInfo:nil]; @throw exp; }
打印结果是:
2015-11-21 20:40:33.999 ExceptionDemo[2136:60b] 4 2015-11-21 20:40:34.296 ExceptionDemo[2136:60b] 5 2015-11-21 20:40:34.775 ExceptionDemo[2136:60b] 6 2015-11-21 20:40:35.254 ExceptionDemo[2136:60b] 7 2015-11-21 20:40:35.813 ExceptionDemo[2136:60b] 8 2015-11-21 20:40:36.429 ExceptionDemo[2136:60b] 9 2015-11-21 20:40:36.983 ExceptionDemo[2136:60b] 10 2015-11-21 20:40:37.597 ExceptionDemo[2136:60b] *** Terminating app due to uncaught exception ‘num > 10‘, reason: ‘num > 10‘ *** First throw call stack: ( 0 CoreFoundation 0x017ec1e4 __exceptio
这里直接崩溃了,如果想不崩溃,继续执行,那么就要用到try catch了
@try { [self.myBox pushIn]; } @catch (NSException *exception) { NSLog(@"%@", exception.reason); } @finally { [self.myBox printNumber]; }
这样就不会崩溃了。
标签:
原文地址:http://www.cnblogs.com/16zj/p/4984628.html