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

查看:32
本文介绍了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:

我想知道何时在objective-c iPhone应用程序中使用try-catch块.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 测试,以确保我,例如,永远不会尝试访问超出数组边界的索引.在这种情况下你会怎么做?

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?

非常感谢!

推荐答案

只适合使用@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.

特别是,它不适合用于捕获越界异常,除非您的目标是捕获它们并以某种方式报告错误,然后——通常——崩溃,或者至少警告用户您的应用处于不一致状态并且可能会丢失数据.

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天全站免登陆