首页 > 解决方案 > 如何根据 Swift 中的数据抛出和处理错误?

问题描述

代码 :

enum PwdError : Error
{
  case obvious;
}

func chkPwd(_ pwd : String) throws -> Bool
{
  if(pwd == "pwd")
  {
    throw PwdError.obvious;
  }

  return true;
}

print(chkPwd("pwd"));

REPL.it 的输出:

Swift version 5.0.1 (swift-5.0.1-RELEASE)
 swiftc -o main main.swift
main.swift:10:5: error: expected expression
    throws PwdError.obvious;
    ^
main.swift:16:7: error: call can throw but is not marked with 'try'
print(chkPwd("pwd"));
      ^~~~~~~~~~~~~
main.swift:16:7: note: did you mean to use 'try'?
print(chkPwd("pwd"));
      ^
      try
main.swift:16:7: note: did you mean to handle error as optional value?
print(chkPwd("pwd"));
      ^
      try?
main.swift:16:7: note: did you mean to disable error propagation?
print(chkPwd("pwd"));
      ^
      try!
compiler exit status 1

在上面的代码中,我试图处理一个错误,但我得到的只是错误。我正在学习 Swift,所以我是新手。到目前为止,我确实在 Java 中工作,所以如果有人用 Java 来解释,那对我来说太棒了。

标签: swift

解决方案


您必须使用try关键字调用该函数

do {
    try chkPwd("pwd")
}
catch {
    print(error) // prints obvious
}

推荐阅读