Objective-C可以开发apple家族系列产品的软件,这里记录成笔记方便日后复习:
- Objective-c学习笔记01——简介
- Objective-c学习笔记02——类(面向对象)
- Objective-c学习笔记03——内存管理
- Objective-c学习笔记04——NSString
- Objective-c学习笔记05——NSArray(NSMutableArray)
- Objective-c学习笔记06——字典与集合
- Objective-c学习笔记07——异常处理(try catch)
一、Oc的异常处理
1 异常处理
Objective – C中提供了异常处理和线程同步,这是解释在这篇文章和“Threading”的支持。要打开这些功能的 支持,使用GNU编译器集(海合会)版本3.3和更高版本的-fobjc-exceptions开关。
2 支持的编译器指令
@try
,@catch
,@throw
,和 @finally
。
代码有可能抛出有可能抛出的异常是封闭在一个@ try块。 @catch()块包含为@ try 块抛出的异常的异常处理逻辑。一个@ finally块包含代码必须执行是否引发异常与否。您可以使用@throw指令抛出一个异常,这基本上是一个对Objective – C对象的指针。你可以使用NSException对象但不限于他们。
- @try {
- < #statements#>
- }
- @catch (NSException *exception) { //捕捉最具体的异常类型
- < #handler#>
- }
- @catch (NSException *ne) { //捕获一个比较重要的异常类型。
- }
- @catch (id ue) { //再次掷出捕获的异常。
- }
- @finally { //不管有没有异常finally内的代码都会执行。
- < #statements#>
- }
二、代码演示
- NSArray * array = @[@"Apple", @"Android", @"Windows"];
- @try {
- array = [NSArray addObject:@"HHH"];
- }
- @catch (NSException *exception) {
- NSLog(@"exception = %@", exception);
- }
- @finally {
- NSLog(@"不管有没有异常我都执行!");
- NSLog(@"%@", array);
- }
- NSException *e = [NSException exceptionWithName:@"CupUnderflowException" reason:@"The level is below 0" userInfo:nil];
- @throw e;
控制台输出:
2013-10-18 15:25:17.990 objective-c——NSArray[11282:303] +[NSArray addObject:]: unrecognized selector sent to class 0x7fff71f701e0 2013-10-18 15:25:17.992 objective-c——NSArray[11282:303] exception = +[NSArray addObject:]: unrecognized selector sent to class 0x7fff71f701e0 2013-10-18 15:25:17.992 objective-c——NSArray[11282:303] 不管有没有异常我都执行! 2013-10-18 15:25:17.993 objective-c——NSArray[11282:303] ( Apple, Android, Windows ) 2013-10-18 15:25:17.994 objective-c——NSArray[11282:303] *** Terminating app due to uncaught exception 'CupUnderflowException', reason: 'The level is below 0' *** First throw call stack: ( 0 CoreFoundation 0x00007fff85f91b06 __exceptionPreprocess + 198 1 libobjc.A.dylib 0x00007fff835113f0 objc_exception_throw + 43 4 libdyld.dylib 0x00007fff83cea7e1 start + 0 ) libc++abi.dylib: terminate called throwing an exception