iOS调试篇: 异常处理(-)

在开发过程中,经常要用到异常处理,防止 程序突然崩溃,在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];
    }

这样就不会崩溃了。

转载于:https://www.cnblogs.com/16zj/p/4984628.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值