经过寻找一些参考的数字出来,-unfortunately-我找不到任何关于理解之间的差异有用-和简单-描述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
或时应遵循的逻辑是什么rethrows
?