在搜索了一些参考资料以弄清楚之后,-不幸的是-我找不到有用的-简单的-关于理解和之间差异的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
必须由 a 处理的函数时try
,与rethrows
. 所以呢?!在决定使用throws
or时我们应该遵循什么逻辑rethrows
?