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


当前回答

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

其他回答

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

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

我认为你永远不应该使用异常来控制正常的程序流程。但是,当某些值与所需值不匹配时,应该抛出异常。

例如,如果某个函数接受一个值,并且该值永远不允许为nil,那么就可以抛出一个异常,而不是尝试做一些“聪明”的事情……

Ries

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

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

使用NSError来传达失败而不是异常。

关于NSError的一些要点:

NSError allows for C style error codes (integers) to clearly identify the root cause and hopefully allow the error handler to overcome the error. You can wrap error codes from C libraries like SQLite in NSError instances very easily. NSError also has the benefit of being an object and offers a way to describe the error in more detail with its userInfo dictionary member. But best of all, NSError CANNOT be thrown so it encourages a more proactive approach to error handling, in contrast to other languages which simply throw the hot potato further and further up the call stack at which point it can only be reported to the user and not handled in any meaningful way (not if you believe in following OOP's biggest tenet of information hiding that is).

参考链接:参考

@throw([NSException exceptionWith…])

Xcode将@throw语句识别为函数出口点,就像return语句一样。使用@throw语法可以避免错误的“Control may reach end of non-void function”警告,你可能会从[NSException raise:…]得到这种警告。

同样,@throw也可以用来抛出不属于NSException类的对象。