蘋果關(guān)于異常的詳細文檔
關(guān)于自定義異常或者擴展:
Objective-C中處理異常是依賴于NSException實現(xiàn)的,它是異常處理的基類,它是一個實體類,而并非一個抽象類,所以你可以直接使用它或者繼承它擴展使用:
1.直接使用,分兩種,拋出默認(rèn)的異常,和自定義自己的新的種類的異常:
OC代碼

#import
intmain (intargc,constchar* argv[])
{
@autoreleasepool {
NSException* ex = [[NSException alloc]initWithName:@"MyException"
reason:@"b==0"
userInfo:nil];
@try
{
intb = 0;
switch(b)
{
case0:
@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];
}
return0;
}
ps:
Initializes and returns a newly allocated exception object.
- (id)initWithName:([NSString](http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/c_ref/NSString)*)*name*reason:([NSString](http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/c_ref/NSString)*)*reason*userInfo:([NSDictionary](http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSDictionary)*)*userInfo*
Parameters
*name*
The name of the exception.
*reason*
A human-readable message string summarizing the reason for the exception.
*userInfo*
A dictionary containing user-defined information relating to the exception
Return Value
The createdNSExceptionobject ornilif the object couldn't be created.
Discussion
This is the designated initializer.
Availability
Available in iOS 2.0 and later.
2.擴展使用,這個推薦你需要自定義一些功能的時候使用,比如,當(dāng)捕獲到指定的異常的時候彈出警告框之類的:
OC代碼

@interface MyException : NSException
-(void)popAlert
@end
Java代碼

@implementationMyException
- (void)popAlert
{
//彈出報告異常原因的警告框 reason
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Tips"
message:self.reason
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil];
[alert show];
[alert release];
}
@end
使用:
OC代碼
- (IBAction)btnClicked_Exception:(id)sender
{
MyException* ex = [[MyException alloc]initWithName:@"MyException"
reason:@"除數(shù)為0了!"
userInfo:nil];
@try
{
intb = 0;
switch(b)
{
case0:
@throw(ex);//b=0,則拋出異常;
break;
default:
break;
}
}
@catch(MyException *exception)//捕獲拋出的異常
{
[exception popAlert];
NSLog(@"b==0 Exception!");
}
@finally
{
NSLog(@"finally!");
}
[ex release];
}
這個時候,捕獲到異常,它就會彈出警告框了。當(dāng)然,你還可以在MyException里面加一些指定的異常的通用處理方法。
只要你愿意,你就可以隨意的定制它!