在objective-c/cocoa中抛出异常的最佳方法是什么?
当前回答
只有在发现自己处于指示编程错误的情况下,并希望停止应用程序运行时,才应该抛出异常。因此,抛出异常的最好方法是使用NSAssert和NSParameterAssert宏,并确保没有定义NS_BLOCK_ASSERTIONS。
其他回答
可以使用两种方法在try catch块中引发异常
@throw[NSException exceptionWithName];
或者第二种方法
NSException e;
[e raise];
这是我从“大书呆子牧场指南(第四版)”中学到的:
@throw [NSException exceptionWithName:@"Something is not right exception"
reason:@"Can't perform this operation because of this or that"
userInfo:nil];
这里有一个警告。在Objective-C中,与许多类似的语言不同,您通常应该尽量避免在正常操作中可能发生的常见错误情况下使用异常。
Apple的Obj-C 2.0文档中写道:“重要的是:异常在Objective-C中是资源密集型的。您不应将异常用于一般的流控制,或仅用于表示错误(例如文件不可访问)”
Apple's conceptual Exception handling documentation explains the same, but with more words: "Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. [.....] Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications."
这样做的部分原因是坚持Objective-C中的编程习惯(在简单的情况下使用返回值,在更复杂的情况下使用按引用参数(通常是NSError类)),部分原因是抛出和捕获异常的代价要高得多,最后(可能是最重要的)Objective-C异常是C的setjmp()和longjmp()函数的一个瘦包装,本质上混乱了你仔细的内存处理,参见下面的解释。
我认为为了保持一致性,最好在你自己的类中使用@throw,它扩展了NSException。然后使用相同的表示法try catch finally:
@try {
.....
}
@catch{
...
}
@finally{
...
}
Apple解释了如何抛出和处理异常:
捕获异常 抛出异常
自从ObjC 2.0以来,Objective-C异常不再是C的setjmp() longjmp()的包装器,并且与c++异常兼容,@try是“免费的”,但抛出和捕获异常的代价要高得多。
无论如何,断言(使用NSAssert和NSCAssert宏家族)抛出NSException,这是明智的使用它们作为Ries状态。
推荐文章
- Java 8: Lambda-Streams,过滤方法与异常
- 为什么ARC仍然需要@autoreleasepool ?
- 首先添加一个UIView,甚至是导航栏
- 我如何改变UIButton标题颜色?
- 如何从UIImage (Cocoa Touch)或CGImage (Core Graphics)获取像素数据?
- 为什么try{…}最后{…}好;尝试{…} catch{}坏?
- iOS -构建失败,CocoaPods无法找到头文件
- Xcode 4挂在“附加到(应用程序名称)”
- 为什么单元测试中的代码不能找到包资源?
- 以编程方式创建segue
- 在Objective-C中@synchronized如何锁定/解锁?
- 为什么在c#中使用finally ?
- Xcode构建失败“架构x86_64未定义的符号”
- 动态改变UILabel的字体大小
- registerForRemoteNotificationTypes: iOS 8.0及以上版本不支持