如何在Swift中向堆栈跟踪传递错误

Jac*_*cob 2 java error-handling exception-handling exception swift

在java中,如果一个方法抛出错误,则调用它的方法可以将其传递给下一个方法.

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");
     }
}
Run Code Online (Sandbox Code Playgroud)

我正在写一个快速的应用程序,并希望做同样的事情.这可能吗?如果不可能有什么其他可能的解决方案?我调用此调用的原始函数具有此结构.

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

}
Run Code Online (Sandbox Code Playgroud)

Ahm*_*d F 7

参考Swift - 错误处理文档,您应该:

1-通过声明符合错误协议的枚举来创建自定义错误类型:

enum CustomError: Error {
    case error01
}
Run Code Online (Sandbox Code Playgroud)

2-声明foo()为throwable函数:

func foo() throws {
    throw CustomError.error01
}
Run Code Online (Sandbox Code Playgroud)

3-声明bar()为throwable函数:

func bar() throws {
    try foo()
}
Run Code Online (Sandbox Code Playgroud)

请注意,虽然bar()是throwable(throws),但它包含throw,为什么?因为它调用foo()(这也是一个抛出错误的函数),try意味着投掷将会明确地进行foo().

为了更清楚:

4-实现test()功能(Do-Catch):

func test() {
    do {
        try bar()
    } catch {
        print("\(error) has been caught!")
    }
}
Run Code Online (Sandbox Code Playgroud)

5-调用test()功能:

test() // error01 has been caught!
Run Code Online (Sandbox Code Playgroud)

如您所见,bar()自动抛出错误,这是指foo()抛出函数错误.