加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 05:34:13 所属栏目:百科 来源:网络整理
导读:我有一个代码块,需要执行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 spe
我有一个代码块,需要执行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 1
Error1

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

Thing 1
Thing 2
Error2

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读