【问题标题】:How to use try-catch in Swift?如何在 Swift 中使用 try-catch?
【发布时间】:2016-06-15 12:01:46
【问题描述】:

我知道如何创建自己的错误并在 Swift 中使用 throws 关键字触发它们。我不明白如何复制在其他语言(或 Ruby rescue)中发现的常规 try - catch 以处理未处理的异常。

示例(在 Swift 中):

func divideStuff(a: Int, by: Int) -> Int {
  return a / by
}

let num = divideStuff(4, by: 0)  //divide by 0 exception

下面是我在 C# 中的处理方式,例如:

int DivideStuff(int a, int b) {
  int result;
  try {
    result = a / b;  
  }
  catch {
    result = 0;
  }
  return result;
}

如何使用 Swift 实现同样的目标?

【问题讨论】:

标签: swift try-catch


【解决方案1】:

在 Swift 中没有捕捉任意运行时错误的功能。
开发者负责正确处理错误。

例如

func divideStuff(a : Int, b : Int) -> Int {
  if b == 0 { return 0 }
  return a / b
}

【讨论】:

  • 谢谢。我不知道 Swift 无法捕获任意运行时错误。不知何故,这感觉很奇怪。
  • 这并不能真正解释 try/catch - 这很好,但它是防御性编程。
【解决方案2】:

你也可以这样处理:

enum MyErrors: ErrorType {
  case DivisionByZero
}

func divideStuff(a: Int, by: Int) throws -> Int {
  if by == 0 {
    throw MyErrors.DivisionByZero
  }
  return a / by
}

let result: Int

do {
  result = try divideStuff(10, by: 0)
} catch {
  // ...
}

【讨论】:

  • 您可能希望在 do/catch 语句中添加一个作为 NSError 的 catch let 错误,以便可以在 catch 部分识别错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2016-06-15
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多