回顾上节的协议,写如下的异常。
@import<Foundation/Foundation.h>
@protocol Test
@optional
-(void) a1;
@end
@import<Foundation/Foundation.h>
#import "Test.h"
@interface User:NSObject <Tset>
@end
#import "User.h"
@implemetation User
@end
#import "User.h"
int main{
User* u=[[User alloc] init];
[u a1];//此处异常
}
进入正题,try catch。和Java一样。
@try{
//异常的代码块
}@catch{
//异常的处理代码
}@finally{
}
注意:避免在@finally中写入return。。。,@throw....。因为当try catch遇到return和throw后会导致方法以及结束。只有@finally执行完毕后程序才会跳过来执行try和catch块中的return和throw语句。,如果在finally中直接使用return和throw,程序会直接停止跳出,不会跳入try catch。