嵌套 – 如何在swift 2.0中处理连续的多次尝试

嵌套 – 如何在swift 2.0中处理连续的多次尝试,第1张

概述我有一个代码块,需要执行2个需要尝试的语句.最好嵌套try,而每个都有自己的do {} catch {} do { try thingOne() do { try thingTwo() } catch let error as NSError { //handle this specific error } } ca 我有一个代码块,需要执行2个需要尝试的语句.最好嵌套try,而每个都有自己的do {} catch {}
do {      try thingOne()     do {         try thingTwo()     } catch let error as NSError {          //handle this specific error     } } catch let error as NSError {      //handle the other specific error here }

…或者将try在一个do block中连续运行?

do {   try thingOne()   try thingTwo()} catch let error as NSError {    //do something with this error}

第二种情况似乎比第一种情况更容易阅读,但是如果其中任何一种会引发错误,那么捕获将会起作用?

然后,我需要区分引起的不同错误,除非错误是通用的,那么这可能并不重要.看看苹果的文档,没有看到任何关于这个.

我认为第二种方式是更好

假设我有这两个功能

func thingOne() throws{      print("Thing 1")      throw CustomError.Type1}func thingTwo() throws{    print("Thing 2")    throw CustomError.Type2}enum CustomError:ErrorType{    case Type1    case Type2}

然后我会这样称呼

do {        try thingOne()        try thingTwo()    } catch CustomError.Type1 {        print("Error1")    } catch CustomError.Type2{        print("Error2")    } catch {        print("Not kNown\(error) ")    }

这将记录

Thing 1Error1

如果thingOne()没有抛出错误,它将记录

Thing 1Thing 2Error2
总结

以上是内存溢出为你收集整理的嵌套 – 如何在swift 2.0中处理连续的多次尝试全部内容,希望文章能够帮你解决嵌套 – 如何在swift 2.0中处理连续的多次尝试所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1038200.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存