美文网首页
2019-09-28 throws与rethrows区别

2019-09-28 throws与rethrows区别

作者: zheNgHH | 来源:发表于2019-09-28 21:47 被阅读0次

新建一个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)")

}

共同点:A rethrowing function or method can contain a throw statement only inside a catch clause.trows function is also too.

以上代码可以正常运行。打印信息如下

essEro2+45

essEro+53

但是以下try callback()块中的语句并没有执行,因为trycallback2()块中的代码print("\(ero.essEro2)+\(#line)")

 throw ero.essEro2中有throw关键词,具有与return相当的功能,trycallback2()后的代码并不会执行。将rehtrows改为throws效果一样,所以是共同点。

如果想调用另一个throws函数,可以在catch语句中调用: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

    }

}

打印信息变为:

essEro2+45

essEro+39

essEro+53

区别一: the catch clause must handle only errors thrown by one of the rethrowing function’s throwing parameters.

若将以下语句注释打开,编译器会提示:A function declared 'rethrows' may only throw if its parameter does,因为函数alwaysThrows()不是参数,rethrows限制了do语句中throws的代码只能是参数中带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

就不会报错了,但还是不会执行alwaysThrows() 函数,因为其在trycallback2()块代码之后,原因即共同点.

区别二: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.

我的理解是类似于rethrowing是throwing的子类,throwing方法不能override rethrowing方法,但是rethrowing方法可以override throwing方法,协议中throwing方法不可以满足rethrowing方法的需求,反之则可以,猜测rethrowing方法的限制比throwing方法的更多

详情参考文档

相关文章

网友评论

      本文标题:2019-09-28 throws与rethrows区别

      本文链接:https://www.haomeiwen.com/subject/avztpctx.html