Objective-C语法之异常解决
发布时间:2021-11-23 13:40:32 所属栏目:PHP教程 来源:互联网
导读:Objective-C的异常比较像Java的异常处理,也有@finally的处理,不管异常是否捕获都都要执行。 异常处理捕获的语法: @try { #statements# } @catch (NSException *exception) { #handler# } @finally { #statements# } @catch{} 块 对异常的捕获应该先细后粗
Objective-C的异常比较像Java的异常处理,也有@finally的处理,不管异常是否捕获都都要执行。 异常处理捕获的语法: @try { <#statements#> } @catch (NSException *exception) { <#handler#> } @finally { <#statements#> } @catch{} 块 对异常的捕获应该先细后粗,即是说先捕获特定的异常,再使用一些泛些的异常类型。 我们自定义两个异常类,看看异常异常处理的使用。 1、新建SomethingException,SomeOverException这两个类,都继承与NSException类。 SomethingException.h #import <Foundation/Foundation.h> @interface SomethingException : NSException @end SomethingException.m #import "SomethingException.h" @implementation SomethingException @end SomeOverException.h #import <Foundation/Foundation.h> @interface SomeOverException : NSException @end SomeOverException.m #import "SomeOverException.h" @implementation SomeOverException @end 2、新建Box类,在某些条件下产生异常。 #import <Foundation/Foundation.h> @interface Box : NSObject { NSInteger number; } -(void) setNumber: (NSInteger) num; -(void) pushIn; -(void) pullOut; -(void) printNumber; @end @implementation Box -(id) init { self = [super init]; if ( self ) { [self setNumber: 0]; } return self; } -(void) setNumber: (NSInteger) num { number = num; if ( number > 10 ) { NSException *e = [SomeOverException exceptionWithName: @"BoxOverflowException" reason: @"The level is above 100" userInfo: nil]; @throw e; } else if ( number >= 6 ) { // throw warning NSException *e = [SomethingException exceptionWithName: @"BoxWarningException" reason: @"The level is above or at 60" userInfo: nil]; @throw e; } else if ( number < 0 ) { // throw exception NSException *e = [NSException exceptionWithName: @"BoxUnderflowException" reason: @"The level is below 0" userInfo: nil]; @throw e; } } -(void) pushIn { [self setNumber: number + 1]; } -(void) pullOut { [self setNumber: number - 1]; } -(void) printNumber { NSLog(@"Box number is: %d", number); } @end ![]() (编辑:云计算网_泰州站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |