Nachdem ich nach einigen Referenzen gesucht hatte, um es herauszufinden, konnte ich leider keine nützliche und einfache Beschreibung zum Verständnis der Unterschiede zwischen throwsund finden rethrows. Es ist etwas verwirrend, wenn man versucht zu verstehen, wie wir sie verwenden sollen.
Ich würde erwähnen, dass ich mit dem -default- throwsmit seiner einfachsten Form zur Verbreitung eines Fehlers wie folgt vertraut bin :
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")
}
}
So weit so gut, aber das Problem entsteht, wenn:
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
}
Was ich bisher weiß, ist beim Aufrufen einer Funktion, dass throwssie im tryGegensatz zu der von a verarbeitet werden muss rethrows. Na und?! Welcher Logik sollten wir folgen, wenn wir uns für throwsoder entscheiden rethrows?