在搜索了一些参考文献以找出它之后,我很难找到有用的简单描述来了解throws
和rethrows
之间的区别。试图了解我们应该如何使用它时,这有点令人困惑。Swift中的抛出和反馈有什么区别?
我会告诉你我有种熟悉的 - 默认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
时,我们应遵循什么逻辑?
很好的回答。谢谢。 – Darko
最后一句话是金色的! – Klaas
所以我想总结一下,当你*可能会抛出时'重新抛出'。当你想**限制为总是投掷时投掷''' – Honey