NSException异常处理
異常處理是管理非典型事件(例如未被識別的消息)的過程,此過程將會中斷正常的程序執行。如果沒有足夠的錯誤處理,遇到非典型事件時,程序可能立刻拋出(或者引發)一種被稱之為異常的東西,然后結束運行。
異常的類型
程序拋出異常的原因多種多樣,可由硬件導致也可由軟件引起。異常的例子很多,包括被零除、下溢和上異之類的數學錯誤,調用未定義的指令(例如,試圖調用一個沒有定義的方法 )以及試圖越界訪問群體中的元素 。
Cocoa異常由NSException對象作為載體,下面是NSException的聲明:
1 @interface NSException : NSObject <NSCopying, NSCoding> { 2 @private 3 NSString *name; 4 NSString *reason; 5 NSDictionary *userInfo; 6 id reserved; 7 }-
A?name?— a short string that is used to uniquely identify the exception. The name is required.
-
A?reason?— a longer string that contains a “human-readable” reason for the exception. The reason is required.
-
An optional dictionary (userInfo) used to supply application-specific data to the exception handler. For example, if the return value of a method causes an exception to be raised, you could pass the return value to the exception handler through?userInfo.
你可以在異常捕獲后提取有用的信息,還可以適當的彈出一個異常警告框。
拋出的異常必須是NSException或者其子類,不能是其他類。
?
下面提供示例代碼:
1 NSException* ex = [[NSException alloc] initWithName:@"ExceptionName" // just for test2 reason:@"XXX"3 userInfo:nil];4 5 CustomNSException* ex = [[CustomNSException alloc] initWithName:@"CustomNSExceptionName" // just for test6 reason:@"XXX"7 userInfo:nil];8 9 @try { 10 bool error = YES; 11 if (error) { 12 @throw ex; 13 } 14 } 15 16 @catch ( CustomNSException *exception ) { 17 NSLog(@"CustomNSException.name = %@" , CustomNSException.name); 18 NSLog(@"CustomNSException.reason = %@" , CustomNSException.reason); 19 20 // 彈出警告框,提示異常信息 21 UIAlertView* alert = [[UIAlertView alloc] initWithTitle:CustomNSException.name 22 message:CustomNSException.reason 23 delegate:nil 24 cancelButtonTitle:nil 25 otherButtonTitles:nil]; 26 27 [alert show]; 28 [alert release]; 29 } 30 31 @catch ( NSException *exception ) { 32 NSLog(@"exception.name = %@" , exception.name); 33 NSLog(@"exception.reason = %@" , exception.reason); 34 } 35 36 @finally { 37 NSLog(@"@finally"); 38 }?
轉載于:https://www.cnblogs.com/fuland/p/3668004.html
總結
以上是生活随笔為你收集整理的NSException异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。