Objective-C:异常的处理

 1 //
 2 //  main.m
 3 //  03-动态绑定
 4 //
 5 //  Created by mac on 15/8/11.
 6 //  Copyright (c) 2015年. All rights reserved.
 7 //
 8 
 9 #import <Foundation/Foundation.h>
10 #import "Fraction.h"
11 #import "Complex.h"
12 #import "MyException.h"
13 int main(int argc, const char * argv[])
14 {
15     @autoreleasepool
16     {
17         //测试分数类
18         Fraction *f1 = [[Fraction alloc]initWithNumerator:1
19                                            addDenominator:2];
20         [f1 print];
21         
22         Fraction *f2 = [[Fraction alloc]initWithNumerator:2
23                                            addDenominator:3];
24         [f2 print];
25         
26         Fraction *f3 = [f1 add:f2];
27         [f3 print];
28         
29         //测试复数类
30         Complex *c1 = [[Complex alloc]initWithReal:5.0 andImag:3.0];
31         [c1 print];
32         
33         Complex *c2 = [[Complex alloc]initWithReal:4.3 andImag:2.5];
34         [c2 print];
35         
36         Complex *c3 = [c1 add: c2];
37         [c3 print];
38         
39         
40         //测试动态绑定
41         id pObj = nil;
42         pObj = f3;
43         [f3 print];
44         
45         pObj = c3;
46         [c3 print];
47         
48         MyException *pe;
49         @try//将容易出现异常的代码放在try代码块里面
50         {
51           id arr[3] = {c1,f1,@""};
52           for(int i=0;i<3;i++)
53           {
54               [arr[i] print];
55               pe = [[MyException alloc] initWithName:@"MyException" reason:@"test" userInfo:nil];
56               @throw pe;//主动抛出自定义的异常
57           }
58             NSLog(@"try last statement");//在出现异常后会跳过@try中后续的代码,不会执行。
59         }
60         @catch(MyException *e)//捕捉自定义的异常
61         {
62             NSLog(@"MyException:%@",[e reason]);
63         }
64         @catch(NSException *e)//系统捕捉异常
65         {
66             NSLog(@"%@",[e reason]);
67         }
68         @finally//最终处理
69         {
70             NSLog(@"finally");
71         }
72         //异常处理完,后续代码会继续执行
73         NSLog(@"last statement!");
74     }
75     return 0;
76 }

 

posted @ 2015-08-11 16:55  XYQ全哥  阅读(283)  评论(0编辑  收藏  举报