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

前端之家收集整理的这篇文章主要介绍了嵌套 – 如何在swift 2.0中处理连续的多次尝试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个代码块,需要执行2个需要尝试的语句.最好嵌套try,而每个都有自己的do {} catch {} @H_403_1@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中连续运行?

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

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

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

我认为第二种方式是更好

假设我有这两个功能

@H_403_1@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 }

然后我会这样称呼

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

这将记录

@H_403_1@Thing 1 Error1

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

@H_403_1@Thing 1 Thing 2 Error2

猜你在找的Swift相关文章