我如何在 swift 2.0 中处理连续多次尝试

How do I handle consecutive multiple try's in swift 2.0

我有一段代码需要执行 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 块中并连续 运行 它们?

do {

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

第二种情况似乎比第一种更容易阅读,但如果其中任何一个抛出错误,catch 会起作用吗?

然后我需要区分抛出的不同错误,除非这些错误足够普遍,否则这可能无关紧要。查看了 Apple 文档,没有看到任何相关信息。

我认为第二种方式更好

假设我有这两个功能

 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