OBject-C捕获异常,常用的异常处理方法

虽然在实际编程中NSException运用不多,但也不妨碍了解一下Cocoa异常编程。

异常处理是管理非典型事件(例如未被识别的消息)的过程,此过程将会中断正常的程序执行。如果没有足够的错误处理,遇到非典型事件时,程序可能立刻抛出(或者引发)一种被称之为异常的东西,然后结束运行。

异常的类型

程序抛出异常的原因多种多样,可由硬件导致也可由软件引起。异常的例子很多,包括被零除、下溢和上异之类的数学错误,调用未定义的指令(例如,试图调用一个没有定义的方法 )以及试图越界访问群体中的元素 。

Cocoa异常由NSException对象作为载体,下面是NSException的声明:

复制代码
1 @interface NSException : NSObject <NSCopying, NSCoding> {
2     @private
3     NSString        *name;
4     NSString        *reason;
5     NSDictionary    *userInfo;
6     id            reserved;
7 }
复制代码
  • name — a short string that is used to uniquely identify the exception. The name is required.

  • reason — a longer string that contains a “human-readable” reason for the exception. The reason is required.

  • An optional dictionary (userInfo) used to supply application-specific data to the exception handler. For example, if the return value of a method causes an exception to be raised, you could pass the return value to the exception handler through userInfo.

你可以在异常捕获后提取有用的信息,还可以适当的弹出一个异常警告框。

抛出的异常必须是NSException或者其子类,不能是其他类。

 

下面提供示例代码:

复制代码
 1     NSException* ex = [[NSException alloc] initWithName:@"ExceptionName"   // just for test
 2                                                  reason:@"XXX"
 3                                               userInfo:nil];
 4     
 5     CustomNSException* ex = [[CustomNSException alloc] initWithName:@"CustomNSExceptionName"   // just for test
 6                                                  reason:@"XXX"
 7                                                userInfo:nil];
 8     
 9     @try {
10         bool error = YES;
11         if (error) {
12             @throw ex;
13         }
14     }
15     
16     @catch ( CustomNSException *exception ) {
17         NSLog(@"CustomNSException.name = %@" , CustomNSException.name);
18         NSLog(@"CustomNSException.reason = %@" , CustomNSException.reason);
19         
20         // 弹出警告框,提示异常信息
21         UIAlertView* alert = [[UIAlertView alloc] initWithTitle:CustomNSException.name
22                                                         message:CustomNSException.reason
23                                                        delegate:nil
24                                               cancelButtonTitle:nil
25                                               otherButtonTitles:nil];
26         
27         [alert show];
28         [alert release];
29     }
30     
31     @catch ( NSException *exception ) {
32         NSLog(@"exception.name = %@" , exception.name);
33         NSLog(@"exception.reason = %@" , exception.reason);
34     }
35     
36     @finally {
37         NSLog(@"@finally");
38     }
复制代码



前言:在开发APP时,我们通常都会需要捕获异常,防止应用程序突然的崩溃,防止给予用户不友好的体验。其实Objective-C的异常处理方法和JAVA的雷同,懂JAVA的朋友一看就懂。我为什么要写这篇博文呢?因为我发现百度上的介绍方法,很多都不是我想要的,而我想要的又说得不清楚,重点是大家都是直接复制别人的代码。。。于是不多说,大家往下看~~~

以下程序已测试并通过:

设备:iOS 8模拟器中

开发工具:XCode6.1

使用@try、catch捕获异常:

以下是最简单的代码写法,其中@finally可以去掉:

1
2
3
4
5
6
7
8
9
@ try  {
     // 可能会出现崩溃的代码
}
@ catch  (NSException *exception) {
     // 捕获到的异常exception
}
@finally {
     // 结果处理
}

在这里举多一具比较详细的方法,抛出异常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ try  {
     // 1
     [self tryTwo];
}
@ catch  (NSException *exception) {
     // 2
     NSLog(@ "%s\n%@" , __FUNCTION__, exception);
//        @throw exception; // 这里不能再抛异常
}
@finally {
     // 3
     NSLog(@ "我一定会执行" );
}
// 4
// 这里一定会执行
NSLog(@ "try" );

tryTwo方法代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
- (void)tryTwo
{
     @ try  {
         // 5
         NSString *str = @ "abc" ;
         [str substringFromIndex:111];  // 程序到这里会崩
     }
     @ catch  (NSException *exception) {
         // 6
//        @throw exception; // 抛出异常,即由上一级处理
         // 7
         NSLog(@ "%s\n%@" , __FUNCTION__, exception);
     }
     @finally {
         // 8
         NSLog(@ "tryTwo - 我一定会执行" );
     }
     
     // 9
     // 如果抛出异常,那么这段代码则不会执行
     NSLog(@ "如果这里抛出异常,那么这段代码则不会执行" );
}

为了方便大家理解,我在这里再说明一下情况:
如果6抛出异常,那么执行顺序为:1->5->6->8->3->4
如果6没抛出异常,那么执行顺序为:1->5->7->8->9->3->4

2)部分情况的崩溃我们是无法避免的,就算是QQ也会有崩溃的时候。因此我们可以在程序崩溃之前做一些“动作”(收集错误信息),以下例子是把捕获到的异常发送至开发者的邮箱。

AppDelegate.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     // Override point for customization after application launch.
     NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
     return  YES;
}
 
void UncaughtExceptionHandler(NSException *exception) {
     /**
      *  获取异常崩溃信息
      */
     NSArray *callStack = [exception callStackSymbols];
     NSString *reason = [exception reason];
     NSString *name = [exception name];
     NSString *content = [NSString stringWithFormat:@ "========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@" ,name,reason,[callStack componentsJoinedByString:@ "\n" ]];
 
     /**
      *  把异常崩溃信息发送至开发者邮件
      */
     NSMutableString *mailUrl = [NSMutableString string];
     [mailUrl appendString:@ "mailto:test@qq.com" ];
     [mailUrl appendString:@ "?subject=程序异常崩溃,请配合发送异常报告,谢谢合作!" ];
     [mailUrl appendFormat:@ "&body=%@" , content];
     // 打开地址
     NSString *mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值