How to pass an Error up the stack trace in Swift

后端 未结 4 2005
日久生厌
日久生厌 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 00:59

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

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

    Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use 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 a do-catch statement,
    • handle the error as an optional value, or
    • assert that the error will not occur.

      Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack

    While Swift errors are used in a similar way to Java's Checked exceptions, they are not quite the same thing.

    Error handling in Swift resembles exception handling in other languages, with the use of the try, catch and throw keywords. Unlike exception handling in many languages—including Objective-C—error handling in Swift does not involve unwinding the call stack, a process that can be computationally expensive. As such, the performance characteristics of a throw statement are comparable to those of a return statement.

    see Swift Error Handling

提交回复
热议问题