Sau khi tìm kiếm một số tài liệu tham khảo để tìm ra nó, thật không may, tôi không thể tìm thấy mô tả hữu ích và đơn giản- về việc hiểu sự khác biệt giữa throwsvà rethrows. Thật là khó hiểu khi cố gắng hiểu cách chúng ta nên sử dụng chúng.
Tôi muốn đề cập rằng tôi khá quen thuộc với -default- throwsvới dạng đơn giản nhất của nó để truyền lỗi, như sau:
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")
}
}
Cho đến nay rất tốt, nhưng vấn đề phát sinh khi:
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
}
những gì tôi biết cho đến nay là khi gọi một hàm, throwsnó phải được xử lý bởi a try, không giống như rethrows. Vậy thì sao?! Logic mà chúng ta nên tuân theo khi quyết định sử dụng throwshoặc là rethrowsgì?