新建一個(gè)playground广辰,將代碼全部替換為下面演示代碼
import UIKit
enum?ero : Error{
? ? case essEro
? ??case essEro2
}
func alwaysThrows() throws {
? ? throw?ero.essEro
}
func?someFunction(callback: ()throws->Void, callback2: ()throws->Void) rethrows{
? ? do{
? ? ? ? try?callback2()
? ? ? ? try?callback()
//? ? ? ? try alwaysThrows()? // Invalid, alwaysThrows() isn't a throwing parameter
? ? }catch{
//? ? ? ? print("2")
? ? ? ? throw?ero.essEro
? ? }
}
do{
? ? try?someFunction(callback: {
? ? ? ? print("\(ero.essEro)+\(#line)")
? ? ? ? throw?ero.essEro
? ? }, callback2: {
? ? ? ? print("\(ero.essEro2)+\(#line)")
? ? ? ? throw?ero.essEro2?
? ? })
}catch(ero.essEro)? {
? ? print("\(ero.essEro)+\(#line)")
}
共同點(diǎn):A rethrowing function or method can contain a?throw?statement only inside a?catch?clause.trows function is also too.
以上代碼可以正常運(yùn)行探熔。打印信息如下
essEro2+45
essEro+53
但是以下try callback()塊中的語(yǔ)句并沒(méi)有執(zhí)行,因?yàn)?b>trycallback2()塊中的代碼print("\(ero.essEro2)+\(#line)")
?throw?ero.essEro2中有throw關(guān)鍵詞,具有與return相當(dāng)?shù)墓δ埽?b>trycallback2()后的代碼并不會(huì)執(zhí)行莫其。將rehtrows改為throws效果一樣倍啥,所以是共同點(diǎn)。
如果想調(diào)用另一個(gè)throws函數(shù),可以在catch語(yǔ)句中調(diào)用:This lets you call the throwing function inside a?do-catch?block and handle errors in the?catch?clause by throwing a different error. 即將改成如下代碼:
func?someFunction(callback: ()throws->Void, callback2: ()throws->Void) rethrows{
?do{
?try?callback2()
//? ? ? ? try alwaysThrows()? // Invalid, alwaysThrows() isn't a throwing parameter
}catch{
//? ? ? ? print("2")
?try?callback()
?throw?ero.essEro
? ? }
}
打印信息變?yōu)椋?/p>
essEro2+45
essEro+39
essEro+53
區(qū)別一:?the?catch?clause must handle only errors thrown by one of the rethrowing function’s throwing parameters.
若將以下語(yǔ)句注釋打開(kāi)措近,編譯器會(huì)提示:A function declared 'rethrows' may only throw if its parameter does溶弟,因?yàn)楹瘮?shù)alwaysThrows()不是參數(shù),rethrows限制了do語(yǔ)句中throws的代碼只能是參數(shù)中帶throws的塊
? ? ? ? //try alwaysThrows()? // Invalid, alwaysThrows() isn't a throwing parameter
如果將
func?someFunction(callback: ()throws->Void, callback2: ()throws->Void) rethrows
改為
func?someFunction(callback: ()throws->Void, callback2: ()throws->Void) throws
就不會(huì)報(bào)錯(cuò)了瞭郑,但還是不會(huì)執(zhí)行alwaysThrows() 函數(shù)辜御,因?yàn)槠湓?b>trycallback2()塊代碼之后,原因即共同點(diǎn).
區(qū)別二:A throwing method can’t override a rethrowing method, and a throwing method can’t satisfy a protocol requirement for a rethrowing method. That said, a rethrowing method can override a throwing method, and a rethrowing method can satisfy a protocol requirement for a throwing method.
我的理解是類(lèi)似于rethrowing是throwing的子類(lèi)屈张,throwing方法不能override rethrowing方法擒权,但是rethrowing方法可以override throwing方法,協(xié)議中throwing方法不可以滿足rethrowing方法的需求阁谆,反之則可以碳抄,猜測(cè)rethrowing方法的限制比throwing方法的更多
詳情參考文檔