在
Swift 3.0中,如何实现通用的do-try-catch块来捕获由于操作而抛出的所有错误. Apple文档说要实现ErrorType类型的枚举器,它列出了抛出的错误.假设我们不知道操作可以抛出哪种错误,那么如何实现它.下面的代码仅用于说明目的.在这里我可以捕获错误但我不知道是什么原因导致此错误.在目标C中,我们可以准确地找出错误发生的原因,但在这里我们只得到我们分配给它的信息.
enum AwfulError: ErrorType{ case CannotConvertStringToIntegertype case general(String)} func ConvertStringToInt( str : String) throws -> Int { if (Int(str) != nil) { return Int(str)! } else { throw AwfulError.general("Oops something went wrong") } } let val = "123a" do { let intval: Int = try ConvertStringToInt(val) print("int value is : \(intval)") } catch let error as NSError { print("Caught error \(error.localizedDescription)") }
do { let str = try NSString(contentsOfFile: "Foo.bar",encoding: NSUTF8StringEncoding) print(str) } catch let error as NSError { print(error.localizedDescription) }
下面的代码不起作用,因为try表达式返回nil.要抛出错误,try表达式应返回错误而不是nil值.类型转换操作是可选的.
do { let intval = try Int("123q") print( Int("\(intval)")) } catch let error as NSError { print(error.localizedDescription) }
解决方法
您可以使用catch来捕获任何类型的错误.
do { try foo() } catch { print(error) }