oc 01 类、异常处理
类的语法
Fraction.h
类声明
#import <Foundation/Foundation.h>
#ifndef Fraction_h
#define Fraction_h
static int t = 0 ; // 类变量
@interface Fraction:NSObject{
int numerator;
@public int denominator;
}
-(void)setNumerator:(int)numerator;
-(void)setDenominator:(int)denominator;
-(void)setNumerator:(int)numerator andDenominator:(int)denominator;
-(int)numerator;
-(int)denominator;
-(void)print; // 成员方法
+(void)t; // 类方法
@end
#endif /* Fraction_h */
Fraction.m
类定义
#import "Fraction.h"
#import "ZeroException.h"
@implementation Fraction
-(void)setNumerator:(int)n{
numerator = n;
}
-(void)setDenominator:(int)d{
if(d==0){
NSException *e = [ZeroException exceptionWithName:@"ZeroException" reason:@"denominator cant be 0!" userInfo:nil];
@throw e; // 抛出异常
}
denominator = d;
}
-(void)setNumerator:(int)n andDenominator:(int)d{
if(d==0){
NSException *e = [ZeroException exceptionWithName:@"ZeroException" reason:@"denominator cant be 0!" userInfo:nil];
@throw e;
}
numerator = n;
denominator = d;
}
-(int)numerator{
return numerator;
}
-(int)denominator{
return denominator;
}
-(void)print{
printf("%d/%d\n",numerator,denominator);
}
+(void)t{
printf("+t:thie class variable t is %d\n",++t);
}
-(NSString*)description{ // toString
return @"I am a fraction";
}
@end
ZeroException.h
异常声明
#import <Foundation/Foundation.h>
@interface ZeroException:NSException
@end
ZeroException.m
异常定义
#import <Foundation/Foundation.h>
#import "ZeroException.h"
@implementation ZeroException
@end
main.c
#import <Foundation/Foundation.h>
#import "Fraction.h"
#import "ZeroException.h"
int main(int argc , const char* argv[])
{
Fraction *frac = [[Fraction alloc]init];
[frac setNumerator:3 andDenominator:4];
[frac print];
[Fraction t];
NSLog(@"%@",frac); // description方法
@try{
[frac setDenominator:0];
}@catch(ZeroException *ze){ // 捕获异常
printf("%s\n",[[ze reason] cString]);
}@finally{
printf("finally run");
}
return 0 ;
}