1 // DivTest.h 2 // 异常的处理 3 // 4 // Created by ma c on 15/8/11. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 10 @interface DivTest : NSObject 11 @property(nonatomic,assign)CGFloat x; 12 @property(nonatomic,assign)CGFloat y; 13 @property(nonatomic,assign)CGFloat div; 14 -(id)initWithX:(CGFloat) m andY:(CGFloat) n; 15 -(void)print; 16 @end
// 上面为类的声明部分
//类的实现部分
1 // DivTest.m 2 // 异常的处理 3 // 4 // Created by ma c on 15/8/11. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import "DivTest.h" 9 #import "MyException.h" 10 @implementation DivTest 11 -(id)initWithX:(CGFloat) m andY:(CGFloat) n 12 { 13 MyException *me; 14 self = [super init]; 15 if(self!=nil) 16 { 17 _x = m; 18 _y = n; 19 if(_y==0) 20 {//如果_y=0,说明除数为零了,抛出异常给调用者去处理 21 @throw me = [[MyException alloc]initWithName:@"MyException:" reason:@"除数为零了" userInfo:nil]; 22 } 23 } 24 return self; 25 } 26 -(void)print 27 { 28 NSLog(@"div:%.2f",_x/_y); 29 } 30 @end
//异常的声明和定义部分
1 // MyException.h 2 // 异常的处理 3 // 4 // Created by ma c on 15/8/11. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 10 @interface MyException : NSException 11 12 @end 13 14 15 // MyException.m 16 // 异常的处理 17 // 18 // Created by ma c on 15/8/11. 19 // Copyright (c) 2015年 bjsxt. All rights reserved. 20 // 21 22 #import "MyException.h" 23 24 @implementation MyException 25 26 @end
//主函数中对异常的测试和处理
1 // main.m 2 // 异常的处理 3 // 4 // Created by ma c on 15/8/11. 5 // Copyright (c) 2015年. All rights reserved. 6 // 7 8 #import <Foundation/Foundation.h> 9 #import "DivTest.h" 10 #import "MyException.h" 11 int main(int argc, const char * argv[]) 12 { 13 @autoreleasepool 14 { 15 DivTest *dt; 16 @try 17 { //检测除数为0的异常 18 dt = [[DivTest alloc]initWithX:4 andY:0]; 19 } 20 @catch(MyException *e) 21 { //捕捉除数为零的异常 22 NSLog(@"MyException:%@",[e reason]); 23 } 24 @catch(NSException *e) 25 { //捕捉其他的异常 26 NSLog(@"Exception:%@",[e reason]); 27 } 28 @finally 29 { //一定要执行的代码块 30 [dt print]; 31 } 32 } 33 return 0; 34 }