我尝试熟悉 Swift 中的 try&catch 结构。 抱歉,我在相关帖子中找不到答案!
是否可以将其隐藏到函数或类中,如此处所示?
class Test {
enum TestError:ErrorType{
case a
case b
}
func a(s:String) throws -> String{
if s == "OK" {
return "OK"
}else{
throw TestError.a
}
}
func b(s:String) throws -> String{
if s == "OK" {
return "OK"
}else{
throw TestError.b
}
}
func doTest(str:String) -> String{
do{
let s = try a(b(str)) // <= ERROR
}catch TestError.a{
return "a failed!"
}catch TestError.b{
return "b failed!"
}
}
} 我总是得到
error: errors thrown from here are not handled because the enclosing catch is not exhaustive
原则上是不可能的,只适用于主程序吗? 或者有解决办法吗?
最佳答案
编译器需要一个子句以防抛出不同的错误。我喜欢像这样通过转换为 NSError 来进行全局捕获:
do {
return try a(b(str))
} catch TestError.a {
return "a failed!"
} catch TestError.b {
return "b failed!"
} catch let error as NSError {
return "\(error.description)"
}
您还必须在 try
处返回字符串。
关于函数或类中的 Swift try-catch 处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37373269/