关于 try catch

2015-10-14 16:13:01 +08:00
 ineed123

由于我比较菜,写 iOS 的,线上 app 出现了一次 crash ,然后主管就问我,为什么你的代码中没有 try catch 。额,然后他还问了:某宝,支付某(号称他以前的同事),然后他们都说 都是这么这么做的。哎,然后我知乎了一下下, http://www.zhihu.com/question/21248079 。哎!

3458 次点击
所在节点    问与答
12 条回复
zwo
2015-10-14 16:46:00 +08:00
try catch 根本就没用,大部分异常都 catch 不到,该崩溃还是崩溃。但是在 swift 下, try-catch 的作用被强化了。
longgeaiwp
2015-10-14 16:50:24 +08:00
try catch 非常有用,我记得知乎上有一个相关问题,里面说的很清楚了。但是 OC 里面 try catch 有点弱鸡那是设计问题了, swift 的 try catch 用途强很多
lion9527
2015-10-14 18:04:29 +08:00
并没什么卵用,而且 catch 段严重影响性能。
曾经试过 5s 一次的 try catch ,真机上超过 2 分钟就挂了。
dorentus
2015-10-14 20:57:25 +08:00
Swift 的是错误处理不是异常捕获,对应的是 Objective-C 里面的 NSError* 作为参数的用法
ffffwh
2015-10-14 22:10:04 +08:00
"都是这么这么做的"
具体怎么做的? catch 到异常是没问题的,怎么恢复运行呢?
ineed123
2015-10-15 09:33:37 +08:00
@zwo 我是的 OC ,我昨天还没时间仔细查,但是好像 try catch 只能捕获一些简单问题,今天看看官方文档咋说。
ineed123
2015-10-15 09:34:45 +08:00
@longgeaiwp 只有你一个人说非常有用,能简单说一下你是怎么用的吗? 是捕获啥?空指针?数组越界?网络异常?
ineed123
2015-10-15 09:35:17 +08:00
@lion9527 吊、
ineed123
2015-10-15 09:36:42 +08:00
@dorentus 网上都是这么说,其实我就很想知道,在 OC 中存在 try catch 的原因是神马?在神马情况下更加倾向于 try catch 呢?
ineed123
2015-10-15 09:39:00 +08:00
@ffffwh 牛人就给了一个“都是这么做的”回答。 但是我记得我看过斯坦福那老头视频里面讲的一段话,说再 OC 中,是不建议使用 try catch 的,也没有必要使用 try catch 来捕获。好像是的,我今天再找找。
dorentus
2015-10-15 10:02:46 +08:00
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/ErrorHandling/ErrorHandling.html

> When you ’ re writing code with Objective-C, exceptions are used solely for programmer errors, like out-of-bounds array access or invalid method arguments. These are the problems that you should find and fix during testing before you ship your app.

> All other errors are represented by instances of the NSError class.

对于 Swift 而言, Exception 无法被捕获和处理,而 NSError 覆盖的情况大部分都改用 do { try ... } catch { ... } 来处理了。
ineed123
2015-10-15 10:49:46 +08:00
@dorentus 谢谢 我也正好看到了。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/227992

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX