日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NSException异常处理

發布時間:2025/7/25 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。