简体   繁体   English

在objective-c中返回错误

[英]Returning errors in objective-c

Im newish to objective-c and am starting to wonder what is the common/standard/proper way for handling and catching errors? 我对objective-c很新,我开始想知道处理和捕获错误的常用/标准/正确方法是什么?

It seems like it might be possible to use NSError to do this, is that a good idea or a hijack of cocoa? 似乎有可能使用NSError来做到这一点,这是一个好主意还是劫持可可?

I'm pretty sure that's what the NSError class is there to do - give details about errors. 我很确定NSError类是做什么的 - 提供有关错误的详细信息。 The most common pattern you'll see is a method that takes a pointer to an NSError object, as in: 您将看到的最常见的模式是一个采用指向NSError对象的指针的方法,如:

- (id)doSomethingWithArgument:(id)arg error:(NSError **)error

The method returns some value (or possibly nil ) for the result of doing something, but if the call failed will place an NSError object at the pointer passed with details about the failure. 该方法为执行某些操作的结果返回一些值(或可能为nil ),但如果调用失败,则会在传递的指针上放置一个NSError对象,其中包含有关失败的详细信息。 Your documentation is responsible for specifying what gets returned if the method does encounter an error. 如果方法遇到错误,您的文档负责指定返回的内容。

The other method that comes to mind is the @throw - @catch block; 想到的另一种方法是@throw - @catch块; however, in Objective-C @throw ing an exception can be rather computationally expensive, and it's usually only recommended to do so in truly exceptional situations. 然而,在Objective-C @throw ,异常可能在计算上相当昂贵,而且通常只建议在真正特殊情况下这样做。

Edit: wow, turns out a lot of people have really strong opinions about @throw ing exceptions. 编辑:哇,事实证明很多人对@throw异常有很强烈的意见。 To sum up the (quite helpful) commentary on the issue: 总结一下(非常有帮助的)关于这个问题的评论:

  • Throwing exceptions should most often deal with programmer error (situations that should never happen, and the like); 抛出异常应该经常处理程序员错误(应该永远不会发生的情况等); exceptions should not be used for ordinary error handling. 异常应用于普通错误处理。 Instead, use the error method demonstrated above or post instances of NSNotification. 相反,使用上面演示的error方法或发布NSNotification的实例。
  • If you do wind up making extensive use of @throw / @catch blocks, be very careful about the logic surrounding them. 如果您最终大量使用@throw / @catch块,请非常小心它们周围的逻辑。 Objective-C provides a lot of ways to detach methods to run in other threads, or delay execution, etc. Be very careful to account for all those possibilities when you write your code. Objective-C提供了许多方法来分离在其他线程中运行的方法,或延迟执行等。在编写代码时要非常小心地考虑所有这些可能性。

Finally, another very valid point: 最后,另一个非常有效的观点:

  • If you do use the error object passed to a method, the return value should indicate it. 如果确实使用传递给方法的error对象,则返回值应指示它。 Don't try to do both (return a partially valid object and set the error object). 不要尝试两者都做(返回部分有效的对象设置error对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM