gpt4 book ai didi

objective-c - iOS 中的异常处理

转载 作者:可可西里 更新时间:2023-11-01 03:28:15 25 4
gpt4 key购买 nike

阅读文档并浏览 Apple 示例代码(以及大部分可用的第三方 Objective-C 代码),我的印象是您不应该使用 try/catch 和“传统方法”进行异常处理/C"方法。
最近在看亚马逊的 AWS iOS SDK,发现他们大肆使用老方法。
这让我松了一口气,因为我总是觉得我需要确保在使用别人编写的代码或二进制库(我指的是 Google Analytics 二进制文件)时特别捕获异常。我的问题是,是否有任何理由在 iOS 上避免“传统的”异常处理“,或者这样做并不是一种有品位的 Objective-C 做法?

最佳答案

在 iOS 上有充分的理由避免异常。

Exceptions on iOS are explicitly reserved for catastrophic failure that cannot be recovered from. They are not intended to be used to do catch-and-recover type operations.

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.

If you have an existing body of code (such as third-party library) that uses exceptions to handle error conditions, you may use the code as-is in your Cocoa application. But you should ensure that any expected runtime exceptions do not escape from these subsystems and end up in the caller’s code. For example, a parsing library might use exceptions internally to indicate problems and enable a quick exit from a parsing state that could be deeply recursive; however, you should take care to catch such exceptions at the top level of the library and translate them into an appropriate return code or state.

这会导致两个问题(除其他外):

  • 你不能通过一帧系统框架代码来@throw 异常。行为未定义。

  • 如果您将代码设计为使用异常,那么您的代码和系统之间的边界就会出现巨大的阻抗不匹配。这不仅会很尴尬,而且随着边界的移动,它会使所有 future 的维护和重构操作变得更加困难。这也会增加与系统集成的难度。

请注意,如果 AWS 开发工具包通过系统框架拥有的堆栈框架抛出异常,那么它就做错了。

关于objective-c - iOS 中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com