Swift:调用可能会抛出错误,但未使用"try"标记,因此错误未得到处理

swiftserver side programmingprogramming更新于 2025/9/22 16:37:17

在 Swift 中,当您调用一个抛出错误的函数时,您必须使用 try 关键字标记该函数调用,或者使用 do-catch 块处理错误。

如果您看到错误消息"调用可能会抛出错误,但未使用"try"标记,因此错误未得到处理",则表示您调用了一个可能会抛出错误的函数,但您尚未正确处理该错误。

如何修复这些错误?

使用 try 关键字标记该函数调用。例如−

do {
    let result = try someFunctionThatCanThrow()
    // 处理结果
} catch {
    // 处理错误
}

使用 do-catch 块处理错误。例如−

do {
    let result = someFunctionThatCanThrow()
    // 处理结果
} catch {
    // 处理错误
}

无论哪种情况,您都需要处理错误,以确保代码健壮并能够处理意外情况。

示例 1

考虑一个函数 divide,它接受两个数字作为输入,并返回第一个数字除以第二个数字的结果。但是,如果第二个数字为零,则该函数会抛出错误。

import Foundation
func divide(_ dividend: Int, by divisor: Int) throws -> Int {
   guard divisor != 0 else {
      throw NSError(domain: "com.example", code: 0, userInfo: [
         NSLocalizedDescriptionKey: "Cannot divide by zero"
      ])
   }
   return dividend / divisor
}

在此示例中,我们使用 throws 关键字标记了该函数,以表明它可以抛出错误。如果除数输入为零,则该函数会抛出错误。

现在,假设我们像这样调用除法函数 -

let result = divide(10, by: 0)

此代码将导致以下错误消息 -

error: call can throw but is not marked with 'try'
let result = divide(10, by: 0)

错误消息告诉我们,除法函数可能会抛出错误,但我们没有用 try 标记该函数调用,也没有处理该错误。

我们可以通过这种方式修复此错误消息 -

import Foundation
func divide(_ dividend: Int, by divisor: Int) throws -> Int {
   guard divisor != 0 else {
      throw NSError(domain: "com.example", code: 0, userInfo: [
         NSLocalizedDescriptionKey: "Cannot divide by zero"
      ])
   }
   return dividend / divisor
}
do {
   let result = try divide(10, by: 0)
   print(result)
} catch let err {
   print("Error found: \(err)")
}

输出

Error found: Error Domain=com.example Code=0 "(null)"

这将捕获除法函数抛出的错误并执行 catch 代码块。

示例 2

在此示例中,我们希望将文件内容读入字符串。我们使用 String(contentsOf:encoding:) 初始化函数来读取文件。但是,如果文件未找到或无法读取,此初始化函数可能会抛出错误。

let filename = "example.txt"
let contents = String(contentsOfFile: filename, encoding: .utf8)
print(contents)

此代码将导致错误消息"调用可以抛出错误,但未标记为'try',并且错误未被处理"。要修复此错误,我们可以将初始化函数标记为 try,或使用 do-catch 代码块处理错误。

import Foundation
let filename = "example.txt"
do {
   let contents = try String(contentsOfFile: filename, encoding: .utf8)
   print(contents)
} catch {
   print(error.localizedDescription)
}

输出

The operation could not be completed. No such file or directory

示例 3

在此示例中,我们需要解析来自 Web 服务的 JSON 数据。我们使用 JSONSerialization.jsonObject(with:options:) 方法来解析 JSON 数据。但是,如果数据不是有效的 JSON,此方法可能会抛出错误。

let data = Data() // 来自 Web 服务的 JSON 数据
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)

此代码将导致错误消息"调用可能抛出错误,但未标记为'try',并且错误未得到处理"。要修复此错误,我们可以用 try 标记该方法,或者使用 do-catch 块处理错误。

解决方案如下 −

import Foundation
let data = Data() // 来自 Web 服务的 JSON 数据
do {
   let json = try JSONSerialization.jsonObject(with: data, options: [])
   print(json)
} catch {
   print(error.localizedDescription)
}

输出

这是将打印到控制台的消息 -

The operation could not be completed. The data is not in the correct format.

结论

在 Swift 中,可以使用 throws 关键字标记函数或方法,以表明它可能抛出错误。调用此类函数或方法时,我们需要使用 try 标记调用,或使用 do-catch 块处理错误。

如果调用可能抛出错误的函数或方法时未使用 try 或处理错误,Swift 将生成编译时错误,并显示"调用可能抛出错误,但未使用'try'标记,因此错误未被处理"。

正确处理错误对于确保代码健壮并能够处理意外情况至关重要。我们应该始终使用 do-catch 块处理错误,或者如果当前层级无法处理错误,则将错误传递给调用者。



相关文章



关于我们 | 隐私条款 | 学习路线
返回顶部