【发布时间】:2017-09-04 10:16:08
【问题描述】:
在搜索了一些参考资料以弄清楚之后,-不幸的是-我找不到有用且简单的描述来了解throws 和rethrows 之间的差异。当试图理解我们应该如何使用它们时,这有点令人困惑。
我会提到,我对 -default- throws 有点熟悉,它最简单的形式用于传播错误,如下所示:
enum CustomError: Error {
case potato
case tomato
}
func throwCustomError(_ string: String) throws {
if string.lowercased().trimmingCharacters(in: .whitespaces) == "potato" {
throw CustomError.potato
}
if string.lowercased().trimmingCharacters(in: .whitespaces) == "tomato" {
throw CustomError.tomato
}
}
do {
try throwCustomError("potato")
} catch let error as CustomError {
switch error {
case .potato:
print("potatos catched") // potatos catched
case .tomato:
print("tomato catched")
}
}
到目前为止一切顺利,但问题出现在:
func throwCustomError(function:(String) throws -> ()) throws {
try function("throws string")
}
func rethrowCustomError(function:(String) throws -> ()) rethrows {
try function("rethrows string")
}
rethrowCustomError { string in
print(string) // rethrows string
}
try throwCustomError { string in
print(string) // throws string
}
到目前为止,我所知道的是,在调用 throws 的函数时,它必须由 try 处理,这与 rethrows 不同。所以呢?!在决定使用throws 或rethrows 时,我们应该遵循什么逻辑?
【问题讨论】:
标签: swift error-handling try-catch throws rethrow