【问题标题】:Swift 2 run code if no exceptions如果没有异常,Swift 2 运行代码
【发布时间】:2015-11-23 16:51:14
【问题描述】:

我目前正在编写一个可能引发错误的 Swift 2 应用程序。为了防止它崩溃我的代码,我使用do-try-catch

在 python 中我们可以这样做:

try:
    functionThatThrowsError()
except exceptionOne:
    pass # exceptionOne was caught 
except exceptionTwo:
    pass # exceptionTwo was caught
else:
    pass # No Errors in code

我目前在 Swift 中有这段代码:

do
{
    try functionThatThrowsError
} catch exceptionOne {
    //Do stuff
} catch exceptionTwo {
    //Do Stuff
}

我将如何在 Swift 2 中做到这一点?

编辑: 'posible duplicate' 不是 Swift do-try-catch syntax 的重复项,因为 do-try-except 不检查代码是否成功执行。

我想做的是这样的:

Run a function that could throw an error
Check for one type of error
    Do code if the error happened
Check for another error type that occurred
    Do code if that error happened
If the function does not throw an error
    Do this code

【问题讨论】:

标签: try-catch swift2


【解决方案1】:
import Foundation

enum Error:ErrorType {
    case Error1
    case Error2
}

func foo() throws -> Void {
    switch arc4random_uniform(3) {
    case 0: throw Error.Error1
    case 1: throw Error.Error2
    default:
        return
    }
}
for i in 0...6 {
    do {
        try foo()
        print("no error code")
        // you can put here as much
        // code, as you need
        let i = random() % 100
        let j = random() % 100
        let k = i + j
        print("\(i) + \(j) = \(k)")
    } catch Error.Error1 {
        print("error 1 code")
    } catch Error.Error2 {
        print("error 2 code")
    }
}

结果

no error code
83 + 86 = 169
error 1 code
error 2 code
error 1 code
no error code
77 + 15 = 92
error 2 code
no error code
93 + 35 = 128

并且要小心,不要将错误和异常混为一谈。这些是完全不同的概念

在你的伪代码中

Run and Ceck a function that could throw for All errors
If the function does not throw an error
Do this code
...
If error1
Do this code
If error2
Do this code

【讨论】:

  • 你能更好地解释一下发生了什么吗?
  • 如果函数没有抛出错误,则执行 do { } 块中的所有后续代码。如果函数抛出错误,则不执行后续代码。所有可能抛出错误的函数都必须跟在关键字try之后
猜你喜欢
  • 2023-04-09
  • 1970-01-01
  • 2019-03-29
  • 1970-01-01
  • 2021-10-13
  • 2013-07-17
  • 1970-01-01
  • 2012-03-30
  • 2015-03-20
相关资源
最近更新 更多