在搜索了一些參考文獻以找出它之後,我很難找到有用的簡單描述來了解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