How to pass an Error up the stack trace in Swift

后端 未结 4 2000
日久生厌
日久生厌 2020-12-04 00:51

In java, if one method throws an error, the method that calls it can pass it on to the next method.

public void foo() throws Exception {
     throw new Excep         


        
4条回答
  •  再見小時候
    2020-12-04 01:06

    Referring to Swift - Error Handling Documentation, you should:

    1- Create your custom error type, by declaring enum which conforms to Error Protocol:

    enum CustomError: Error {
        case error01
    }
    

    2- Declaring foo() as throwable function:

    func foo() throws {
        throw CustomError.error01
    }
    

    3- Declaring bar() as throwable function:

    func bar() throws {
        try foo()
    }
    

    Note that although bar() is throwable (throws), it does not contain throw, why? because it calls foo() (which is also a function that throws an error) with a try means that the throwing will -implicitly- goes to foo().

    To make it more clear:

    4- Implement test() function (Do-Catch):

    func test() {
        do {
            try bar()
        } catch {
            print("\(error) has been caught!")
        }
    }
    

    5- Calling test() function:

    test() // error01 has been caught!
    

    As you can see, bar() automatically throws error, which is referring to foo() function error throwing.

提交回复
热议问题