如何在 Swift 中将错误向上传递到堆栈跟踪 [英] How to pass an Error up the stack trace in Swift

查看:26
本文介绍了如何在 Swift 中将错误向上传递到堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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");
     }
}

我正在 swift 编写一个应用程序,并且想做同样的事情.这可能吗?如果不可能,还有哪些其他可能的解决方案?我原来的调用函数就是这个结构.

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 {

}

推荐答案

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

1- 通过声明符合 错误协议:

1- Create your custom error type, by declaring enum which conforms to Error Protocol:

enum CustomError: Error {
    case error01
}

2-foo() 声明为可抛出函数:

2- Declaring foo() as throwable function:

func foo() throws {
    throw CustomError.error01
}

3-bar() 声明为可抛出函数:

3- Declaring bar() as throwable function:

func bar() throws {
    try foo()
}

请注意,虽然 bar() 是可抛出的(throws),但它包含 throw,为什么?因为它使用 try 调用 foo()(这也是一个抛出错误的函数)意味着抛出将 - 隐式 - 转到 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().

为了更清楚:

4- 实现 test() 函数(Do-Catch):

4- Implement test() function (Do-Catch):

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

5- 调用 test() 函数:

test() // error01 has been caught!

可以看到,bar()自动抛出错误,指的是foo()函数错误抛出.

As you can see, bar() automatically throws error, which is referring to foo() function error throwing.

这篇关于如何在 Swift 中将错误向上传递到堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆