How to pass an Error up the stack trace in Swift

后端 未结 4 2002
日久生厌
日久生厌 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:01

    A Swift function can call a throwing function and pass an error up to the caller, but

    • The function itself must be marked with throws, and
    • the throwing function has to be called with try.

    Example:

    func foo() throws {
        print("in foo")
        throw NSError(domain: "mydomain", code: 123, userInfo: nil)
    }
    
    func bar() throws -> String {
        print("in bar")
        try foo()
        return "bar"
    }
    
    do {
        let result = try bar()
        print("result:", result)
    } catch {
        print(error.localizedDescription)
    }
    

    Output:

    in bar
    in foo
    The operation couldn’t be completed. (mydomain error 123.)
    

    If try foo() fails then bar() returns immediately, propagating the error thrown by foo() to its caller. In other words, try foo() inside a throwing function is equivalent to

    do {
        try foo()
    } catch let error {
        throw error
    }
    

提交回复
热议问题