我正在处理一个实现了 do-try-catch 子句的类。 基本上问题是即使尝试失败,“try”之后的代码也会被执行:
Do{
try jsonparshing(mydata)
code....
}catch{
alert("error")
}
尝试后定位到的代码是否正确? 我不希望在尝试失败时执行此代码。
最佳答案
以下是我要执行的调试该行为的步骤:
(1) 你的“jsonparshing(mydata)”真的会抛出异常吗?
1.a.您可以检查“jsonParsing(_:)”的类型来查找 throws 关键字。
1.b。或者您可以尝试完全省略“do { } catch {}”和“try”,看看 Xcode 是否提示该函数抛出异常并应该使用 try。
//顺便说一句。这是一个错字吗?也许“jsonParsing(myData)”更自定义。
(2) 假设您已办理登机手续 (1)。 IE。该函数确实抛出了异常。然后,您可以将“jsonParsing(_:)”替换为模拟的“jsonParsing(_:)”,只是为了让自己相信 Swift“do {} catch {}”确实有效。您的代码中可能还有其他内容可能导致意外行为。
enum SimpleError: Error {
case userError(msg: String)
case systemError(msg: String)
}
func alwaysThrow() throws -> () {
throw SimpleError.userError(msg: "I create error!")
}
do {
print("before throw") // printed
try alwaysThrow()
print("after throw") // not printed
} catch {
print(error) // print: "userError("I create error!")\n"
}
(3) 此时,如果不是用户/程序员错误,请将注意力集中在“jsonParsing(_:)”上,因为这就是罪魁祸首。
关于Swift Do Try Catch 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44204869/