---
title: "Objective-C语法之异常处理 ."
author: "android_zhang"
date: "2013-01-05T09:45:59Z"
tags: ["Objective-C"]
categories: ["移动开发"]
slug: "objective-c"
draft: false
lastmod: "2013-01-05T09:45:59Z"
id: 1758136
url: "https://android-zhang.iteye.com/blog/1758136"
---

Objective-C的异常比较像Java的异常处理，也有@finally的处理，不管异常是否捕获都都要执行。
异常处理捕获的语法：


```java
  @try {
        <#statements#>
    }
    @catch (NSException *exception) {
        <#handler#>
    }
    @finally {
        <#statements#>
    }
```



 @catch{} 块 对异常的捕获应该先细后粗，即是说先捕获特定的异常，再使用一些泛些的异常类型。
我们自定义两个异常类，看看异常异常处理的使用。

SomethingException.h


```java
#import <Foundation/Foundation.h>

@interface SomethingException : NSException

@end
```


SomethingException.m

```java
#import "SomethingException.h"

@implementation SomethingException

@end
```


SomeOverException.h

```java
#import <Foundation/Foundation.h>

@interface SomeOverException : NSException

@end
```


SomeOverException.m

```java
#import "SomeOverException.h"

@implementation SomeOverException

@end
```





2、新建Box类，在某些条件下产生异常。

```java
#import <Foundation/Foundation.h>

@interface Box : NSObject
{
    NSInteger number;
}
-(void) setNumber: (NSInteger) num;
-(void) pushIn;
-(void) pullOut;
-(void) printNumber;
@end
```



```java
@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
```




这个类的作用是，初始化Box时，number数字是0，可以用pushIn 方法往Box里推入数字，每调用一次，number加1.当number数字大于等于6时产生SomethingException异常,告诉你数字达到或超过6了，超过10时产生SomeOverException异常，小于1时产生普通的NSException异常。
这里写 - (void)viewDidLoad
{
    ;    
    NSAutoreleasePool *pool =  init];
    Box *box = init];
    for (int i = 0; i < 5; i++) {
        ;
        ;
    }
}
打印结果：
Box number is: 1

Box number is: 2

Box number is: 3

Box number is: 4

Box number is: 5



3.2 超过6，产生异常

```java
for (int i = 0; i < 11; i++) {
            [box pushin];
            [box printnumber];
    }
```


```java
2012-07-04 09:12:05.889 ObjectiveCTest[648:f803] Box number is: 1
2012-07-04 09:12:05.890 ObjectiveCTest[648:f803] Box number is: 2
2012-07-04 09:12:05.890 ObjectiveCTest[648:f803] Box number is: 3
2012-07-04 09:12:05.890 ObjectiveCTest[648:f803] Box number is: 4
2012-07-04 09:12:05.891 ObjectiveCTest[648:f803] Box number is: 5
2012-07-04 09:12:05.891 ObjectiveCTest[648:f803] *** Terminating app due to uncaught exception 'BoxWarningException', reason: 'The number is above or at 60'
```


这是时，程序抛出异常崩溃了。那怎么使程序不崩溃呢，做异常处理。






3.3、加上异常处理

```java
for (int i = 0; i < 11; i++) {
        @try {
            [box pushin];
        }
        @catch (SomethingException *exception) {
            NSLog(@"%@ %@", [exception name], [exception reason]);
        }
        @catch (SomeOverException *exception) {
            NSLog(@"%@", [exception name]);
        }
        @finally {
            [box printnumber];
        }
    }
```

运行，程序没有崩溃，打印结果：

```java
2012-07-04 09:14:35.165 ObjectiveCTest[688:f803] Box number is: 1
2012-07-04 09:14:35.167 ObjectiveCTest[688:f803] Box number is: 2
2012-07-04 09:14:35.167 ObjectiveCTest[688:f803] Box number is: 3
2012-07-04 09:14:35.167 ObjectiveCTest[688:f803] Box number is: 4
2012-07-04 09:14:35.167 ObjectiveCTest[688:f803] Box number is: 5
2012-07-04 09:14:35.167 ObjectiveCTest[688:f803] BoxWarningException The number is above or at 60
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] Box number is: 6
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] BoxWarningException The number is above or at 60
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] Box number is: 7
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] BoxWarningException The number is above or at 60
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] Box number is: 8
2012-07-04 09:14:35.168 ObjectiveCTest[688:f803] BoxWarningException The number is above or at 60
2012-07-04 09:14:35.169 ObjectiveCTest[688:f803] Box number is: 9
2012-07-04 09:14:35.169 ObjectiveCTest[688:f803] BoxWarningException The number is above or at 60
2012-07-04 09:14:35.169 ObjectiveCTest[688:f803] Box number is: 10
2012-07-04 09:14:35.169 ObjectiveCTest[688:f803] BoxOverflowException
2012-07-04 09:14:35.225 ObjectiveCTest[688:f803] Box number is: 11
```


超过10时，SomeOverException异常抛出。






3.4 、小于0时的异常
在Box类的setNumber里，当number小于0时，我们抛出普通异常。

```java
  @try {
        [box setnumber:-10];
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception name]);
    }
    @finally {
        [box printnumber];
    }
```

打印结果：

```java
2012-07-04 09:17:42.405 ObjectiveCTest[753:f803] BoxUnderflowException
2012-07-04 09:17:42.406 ObjectiveCTest[753:f803] Box number is: -10
```