How to pass an Error up the stack trace in Swift

error-handling, exception, java, swift

Solution

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.

Problem

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 Exception(); } public void bar() throws Exception { foo(); } public static void main(String args[]) { try { bar(); } catch(Exception e) { System.out.println("Error"); } } ``` I am writing an app in swift and would like to do the same thing. Is this possible? If it is not possible what are some other possible solutions? My original function that makes the call has this structure. ``` func convert(name: String) throws -> String { } ```

Original source