How to pass error on stack in Swift

In java, if one method throws an error, the method that calls it can pass it 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 application quickly and would like to do the same. Is it possible? If this is not possible, what other possible solutions? My original function that makes the call has this structure.

func convert(name: String) throws -> String {

}

      

0


source to share


4 answers


When referencing Swift - Error Handling Documentation , you should:

1 - Create your own error type by declaring an enum that matches the Error Log :

enum CustomError: Error {
    case error01
}

      

2 - Declaration foo()

as a throwable function:

func foo() throws {
    throw CustomError.error01
}

      

3 - Declaration bar()

as a drop function:

func bar() throws {
    try foo()
}

      



Note that although bar()

throwable ( throws

) is, it doesn't contain throw

, why? because it calls foo()

(which is also the function that throws the error) with try

means that the meta-cast will be-multiplied by foo()

.

To make it clearer:

4 - Implement a function test()

(Do-Catch):

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

      

5 - Calling the function test()

:

test() // error01 has been caught!

      

As you can see, it bar()

automatically throws an error that refers to foo()

the function firing.

+4


source


Swift function can call throw

ing function and pass the error up to the caller, but

  • The function itself must be checked throws

    and
  • the throwing function must 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 it try foo()

fails, it bar()

returns immediately, propagating an error that is thrown by foo()

its caller. In other words, try foo()

inside a throw function is equivalent to

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

      

+2


source


Swift handles error propagation and has no exception mechanism. In Swift, a called function can pass the error it encounters in the context from which it was called. But despite using the keyword throw

, it doesn't actually throw an exception. It simply passes the error through a pipe other than the function's return value.

My guess is that the caller subroutine can then interpret the error in the function it called as the error itself and pass the associated error to the caller, but there is generally no mechanism in Swift for you to jump through the frame stack when an error condition is encountered ...

0


source


In Swift, errors are represented by values ​​of types that conform to the Error protocol. This empty log indicates that the type can be used for error handling.

In Swift Only throwing functions can propagate bugs . Any errors that occur inside a nonthrowing function must be handled inside the function.

Throwing an error allows you to indicate that something unexpected has happened and the normal flow of execution cannot continue. You are using a throw statement to throw an error.

There are four ways to handle errors in Swift.

  • You can propagate the error from a function to the code that calls that function,
  • handle the error using the do-catch statement,
  • treats the error as optional, or
  • argue that there will be no error.

    Unlike exception handling in many languages, including Objective-C -error, handling in Swift does not involve expanding the call stack.

While Swift errors are used similarly to Java Checked exceptions, they are not exactly the same.

Swift's error handling is similar to the exception handling in other languages ​​using the try, catch, and throw keywords. Unlike exception handling in many languages, including Objective-C-error handling in Swift does not involve expanding the call stack, a process that can be costly. Thus, the performance characteristics of a throw statement are comparable to those of a return statement.

see Swift Error Handling

0


source







All Articles