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

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

问题描述

  throw new Exception(); 
}
public void bar()throws Exception {
foo();
}
public static void main(String args []){
try {
bar();
}
catch(异常e){
System.out.println(Error);
}
}

我正在迅速写一个应用程序,做同样的事。这可能吗?如果不可能有什么其他可能的解决方案?我的原始函数使得调用具有这种结构。

  func convert(name:String)throws  - >字符串{

}


解决方案

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



1 - 创建您的自定义错误类型,通过声明符合错误协议

 枚举CustomError:错误{
case error01
}

2 - 声明 foo() function:

  func foo()throws {
throw CustomError.error01
}

3 - 声明 bar() function:

  func bar()throws {
try foo()
}

没有te, bar()确实会抛出,但它不包含 throw ,为什么?因为它调用 foo()(它也是一个引发错误的函数)与 try 意味着投掷将明确地转到 foo()



为了使之更清楚:



4 - 实现 test() function(Do-Catch):

  func test(){
do {
try bar()
} catch {
print( \\(错误)已被抓住!)
}
}

strong> 5 - 调用 test() function:

  test()// error01已被抓住! 

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


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 {

}

解决方案

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() function:

func foo() throws {
    throw CustomError.error01
}

3- Declaring bar() function:

func bar() throws {
    try foo()
}

Note that bar() does throws, but it does not contains 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.

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

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