swift try try? try!

try

You have 2 options when you try calling a function that may throw.

You can take responsibility of handling errors by surrounding your call within a do-catch block:

Or just try calling the function, and pass the error along to the next caller in the call chain:

try!

What happens when you try to access an implicitly unwrapped optional with a nil inside it? Yes, true, the app will CRASH! Same goes with try! it basically ignores the error chain, and declares a “do or die” situation. If the called function didn’t throw any errors, everything goes fine. But if it failed and threw an error, your application will simply crash.

try?

A new keyword that was introduced in Xcode 7 beta 6. It returns an optional that unwraps successful values, and catches error by returning nil.

Or we can use new awesome guard keyword:

One final note here, by using try? note that you’re discarding the error that took place, as it’s translated to a nil. Use try? when you’re focusing more on successes and failure, not on why things failed.

 

https://stackoverflow.com/questions/32390611/try-try-try-what-s-the-difference-and-when-to-use-each

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值