swift - 如何根据 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 来解释,那对我来说太棒了。
解决方案
您必须使用try
关键字调用该函数
do {
try chkPwd("pwd")
}
catch {
print(error) // prints obvious
}
推荐阅读
- excel - 从单元格中删除所有图像,除了 vba 中的最后一个
- variables - ELProcessor - 如何将一个参数动态传递给 setValue() 方法?
- c++ - 输入字符时 cin 跳过
- macos - 如何以编程方式获取有关 MacOS 上活动 DNS 配置文件的信息?
- gremlin - AWS Neptune HTTP REST 将响应序列化程序从 GraphSON 更改为 JSON
- java - setBounds 不适用于 Java 中的 TextField
- google-apps-script - 针对特定项目谷歌表交叉更新同一工作表中两列的数据
- python - 如果另一列与某个值匹配,则分配该列的值
- c++ - 为每个子窗口设置唯一标识符
- lua - 是否可以防止在lua中打印字符串