NSException与NSError区别?


NSException与NSError在使用中有哪些区别?

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        NSException* ex = [[NSException alloc]initWithName:@"MyException"  
                                                    reason:@"b==0"   
                                                  userInfo:nil];  

        @try   
        {  
            int b = 0;   
            switch (b)    
            {  
                case 0:  
                    @throw(ex);//b=0,则抛出异常;  
                    break;  
                default:  
                    break;  
            }  
        }  
        @catch (NSException *exception)//捕获抛出的异常   
        {  
            NSLog(@"exception.name= %@" ,exception.name);
            NSLog(@"exception.reason= %@" ,exception.reason);
            NSLog(@"b==0 Exception!");  
        }  
        @finally   
        {  
            NSLog(@"finally!");  
        }  
        [ex release];  

    }
    return 0;
}

https://developer.apple.com/library/m...

https://developer.apple.com/library/m...

objective-c cocoa-touch

你爸爸的男朋友 11 years, 5 months ago

异常和错误是完全不同的两个东西。如果抛出个异常但是你没捕获,那就会crash,但是如果是返回个错误,对外部来说可以随意怎么办,只是告诉你这个调用有错误。

Yuzeki answered 11 years, 5 months ago

Your Answer