iPhone / Objective-C的try-catch异常处理实践 [英] Try-catch exception handling practice for iPhone/Objective-C

查看:81
本文介绍了iPhone / Objective-C的try-catch异常处理实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题已经在其他地方得到回答,请问如果这个问题已经被解决了,但是在搜索时找不到任何决定性的答案:

Apologies if this question has already been answered somewhere else, but I could not find any decisive answer when searching on it:

我想知道什么时候try-catch块应用于客观C iPhone应用程序。 Apple的Objective-C编程语言简介指出,异常是资源密集型的,应该不使用例外来进行一般的流程控制,或仅仅表示错误。从这里阅读几个相关的问题,我也会收集到,人们并不经常在实践中使用这种方法。

I'm wondering when try-catch blocks are to be used in objective-c iPhone applications. Apple's "Introduction to the Objective-C Programming Language" state that exceptions are resource intensive and that one should "not use exceptions for general flow-control, or simply to signify errors." From reading a few related questions here I also gather that people are not often using this method in practice.

所以我猜问题是:适当的情况是什么在开发iPhone / Objective-C时使用try-catch块,何时应该绝对不使用?

So I guess the question is: what are the situations when it's appropriate to use try-catch blocks when developing for iPhone/Objective-C and when should they absolutely NOT be used?

例如,我可以使用它们来捕捉超越边界,处理数组中的对象时的其他异常。我有一个方法,执行几个任务与对象在多个数组中传递。如果发生错误,该方法返回nil,并且try-catch块可以帮助我捕获异常。然而,我当然可以在这里和那里写一些if-tests,以确保我,例如,永远不要尝试访问数组范围以外的索引。在这种情况下你会做什么?

For example, I could use them to catch beyond bounds and other exceptions when working with objects in arrays. I have a method which performs are few tasks with objects that are passed on in a number of arrays. The method returns nil if an error has occurred and a try-catch block could help me catch exceptions. However, I could of course simply write little if-tests here and there to ensure that I, for instance, never try to access an index beyond an arrays bounds. What would you do in this situation?

非常感谢!

推荐答案

p>只能使用@ try / @ catch来处理不可恢复的错误。使用@ throw / @ try / @ catch来执行控制流这样的操作是不合适的。

It is only appropriate to use @try/@catch to deal with unrecoverable errors. It is never appropriate to use @throw/@try/@catch to do control-flow like operations.

特别的是,不适合用来捕捉-of-bounds异常,除非你的目标是抓住他们,以某种方式报告错误,然后 - 通常 - 崩溃,或者至少警告用户你的应用程序处于不一致状态,并可能丢失数据。

In particular, it would not be appropriate to use for catching out-of-bounds exceptions unless your goal is to catch them and somehow report the error, then -- typically -- crash or, at the least, warn the user that your app is in an inconsistent state and may lose data.

通过系统框架代码抛出的异常的行为是未定义的。

Behavior of any exception thrown through system framework code is undefined.

您的if-test做边界检查是一个很大的更合适的解决方案。

Your if-test to do bounds checking is a far more appropriate solution.

这篇关于iPhone / Objective-C的try-catch异常处理实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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