objective-c中的返回错误 [英] Returning errors in objective-c

查看:130
本文介绍了objective-c中的返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Im newish to objective-c,我开始怀疑什么是处理和捕获错误的常见/标准/正确的方法?



这似乎可能使用NSError来做到这一点,是一个好主意还是可可的劫持?

解决方案

我很确定这是NSError类是做什么 - 提供错误的详细信息。你会看到最常见的模式是一个方法,它接受一个指向NSError对象的指针,如:

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

该方法返回一些值c $ c> nil ),但是如果调用失败,将在传递的指针上传递一个NSError对象。



另一种方法是 @throw

/ code> - @catch 块;但是,在Objective-C @throw 中,异常的计算量可能相当昂贵,通常只有在真正异常的情况下才这样做。



编辑:哇,结果很多人对 @throw 例外感到非常强烈的意见。




  • 抛出异常通常会处理程序员错误(情况应该从不发生,等等);例外不应用于普通错误处理。而是使用上面展示的错误方法或NSNotification的后置实例。

  • 如果您确实充分利用了 @throw / @catch 块,对它们周围的逻辑要非常小心。 Objective-C提供了很多方法来分离方法在其他线程中运行,或者延迟执行等。在编写代码时要非常小心地考虑所有这些可能性。



最后,另一个非常有效的点:




  • 如果你使用 error 传递给方法的对象,返回值应该指示它。不要尝试同时执行(返回部分有效的对象设置错误对象)。


    • Im newish to objective-c and am starting to wonder what is the common/standard/proper way for handling and catching errors?

      It seems like it might be possible to use NSError to do this, is that a good idea or a hijack of cocoa?

      解决方案

      I'm pretty sure that's what the NSError class is there to do - give details about errors. The most common pattern you'll see is a method that takes a pointer to an NSError object, as in:

      - (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. 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; however, in Objective-C @throwing an exception can be rather computationally expensive, and it's usually only recommended to do so in truly exceptional situations.

      Edit: wow, turns out a lot of people have really strong opinions about @throwing exceptions. 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.
      • If you do wind up making extensive use of @throw/@catch blocks, be very careful about the logic surrounding them. 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.

      Finally, another very valid point:

      • If you do use the error object passed to a method, the return value should indicate it. Don't try to do both (return a partially valid object and set the error object).

      这篇关于objective-c中的返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆