歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Objective-C語法之異常處理

Objective-C語法之異常處理

日期:2017/3/1 10:17:50   编辑:Linux編程
Objective-C的異常比較像Java的異常處理,也有@finally的處理,不管異常是否捕獲都都要執行。 異常處理捕獲的語法:
  1. @try {
  2. <#statements#>
  3. }
  4. @catch (NSException *exception) {
  5. <#handler#>
  6. }
  7. @finally {
  8. <#statements#>
  9. }
@catch{} 塊 對異常的捕獲應該先細後粗,即是說先捕獲特定的異常,再使用一些泛些的異常類型。 我們自定義兩個異常類,看看異常異常處理的使用。

1、新建SomethingException,SomeOverException這兩個類,都繼承與NSException類。

SomethingException.h
  1. #import <Foundation/Foundation.h>
  2. @interface SomethingException : NSException
  3. @end
SomethingException.m
  1. #import "SomethingException.h"
  2. @implementation SomethingException
  3. @end
SomeOverException.h
  1. #import <Foundation/Foundation.h>
  2. @interface SomeOverException : NSException
  3. @end
SomeOverException.m
  1. #import "SomeOverException.h"
  2. @implementation SomeOverException
  3. @end

2、新建Box類,在某些條件下產生異常。

  1. #import <Foundation/Foundation.h>
  2. @interface Box : NSObject
  3. {
  4. NSInteger number;
  5. }
  6. -(void) setNumber: (NSInteger) num;
  7. -(void) pushIn;
  8. -(void) pullOut;
  9. -(void) printNumber;
  10. @end
  1. @implementation Box
  2. -(id) init {
  3. self = [super init];
  4. if ( self ) {
  5. [self setNumber: 0];
  6. }
  7. return self;
  8. }
  9. -(void) setNumber: (NSInteger) num {
  10. number = num;
  11. if ( number > 10 ) {
  12. NSException *e = [SomeOverException
  13. exceptionWithName: @"BoxOverflowException"
  14. reason: @"The level is above 100"
  15. userInfo: nil];
  16. @throw e;
  17. } else if ( number >= 6 ) {
  18. // throw warning
  19. NSException *e = [SomethingException
  20. exceptionWithName: @"BoxWarningException"
  21. reason: @"The level is above or at 60"
  22. userInfo: nil];
  23. @throw e;
  24. } else if ( number < 0 ) {
  25. // throw exception
  26. NSException *e = [NSException
  27. exceptionWithName: @"BoxUnderflowException"
  28. reason: @"The level is below 0"
  29. userInfo: nil];
  30. @throw e;
  31. }
  32. }
  33. -(void) pushIn {
  34. [self setNumber: number + 1];
  35. }
  36. -(void) pullOut {
  37. [self setNumber: number - 1];
  38. }
  39. -(void) printNumber {
  40. NSLog(@"Box number is: %d", number);
  41. }
  42. @end
這個類的作用是,初始化Box時,number數字是0,可以用pushIn 方法往Box裡推入數字,每調用一次,number加1.當number數字大於等於6時產生SomethingException異常,告訴你數字達到或超過6了,超過10時產生SomeOverException異常,小於1時產生普通的NSException異常。

這裡寫 [SomeOverException exceptionWithName:@"BoxOverflowException" reason:@"The level is above 100"異常的名稱和理由,在捕獲時可以獲取。

Copyright © Linux教程網 All Rights Reserved