swift try try? try!

Posted feng9exe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于swift try try? try!的主要内容,如果未能解决你的问题,请参考以下文章

Swift 4 中不确定代码块的 Try-catch 功能

php 一个自定义的try..catch包装器代码片段,用于执行模型函数,使其成为一个单行函数调用

Swift 错误未处理且未标有 try

通过 try 块处理 Swift 2.2 错误

swift 2.x 如何使用try catch

异常和TCP通讯