在objective-c/cocoa中抛出异常的最佳方法是什么?


当前回答

这是我从“大书呆子牧场指南(第四版)”中学到的:

@throw [NSException exceptionWithName:@"Something is not right exception"
                               reason:@"Can't perform this operation because of this or that"
                             userInfo:nil];

其他回答

我使用[NSException raise:format:]如下所示:

[NSException raise:@"Invalid foo value" format:@"foo of %d is invalid", foo];

只有在发现自己处于指示编程错误的情况下,并希望停止应用程序运行时,才应该抛出异常。因此,抛出异常的最好方法是使用NSAssert和NSParameterAssert宏,并确保没有定义NS_BLOCK_ASSERTIONS。

这是我从“大书呆子牧场指南(第四版)”中学到的:

@throw [NSException exceptionWithName:@"Something is not right exception"
                               reason:@"Can't perform this operation because of this or that"
                             userInfo:nil];

Regarding [NSException raise:format:]. For those coming from a Java background, you will recall that Java distinguishes between Exception and RuntimeException. Exception is a checked exception, and RuntimeException is unchecked. In particular, Java suggests using checked exceptions for "normal error conditions" and unchecked exceptions for "runtime errors caused by a programmer error." It seems that Objective-C exceptions should be used in the same places you would use an unchecked exception, and error code return values or NSError values are preferred in places where you would use a checked exception.

自从ObjC 2.0以来,Objective-C异常不再是C的setjmp() longjmp()的包装器,并且与c++异常兼容,@try是“免费的”,但抛出和捕获异常的代价要高得多。

无论如何,断言(使用NSAssert和NSCAssert宏家族)抛出NSException,这是明智的使用它们作为Ries状态。