Swift 使用throws抛出异常使用方法:
我在开发中遇到带有抛出异常的关键字throws标注的方法,直接调用会报错,具体如下:
函数:
public func createDirectoryAtPath(path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [String : AnyObject]?) throws
调用:
搜索: Call can throw, but it is not marked with 'try' and the error is not handled未能找到我要的结果,
在网上查阅一下资料,发现swift版本更新之前时 ,代码:
fileManager.createDirectoryAtPath(mydir2, withIntermediateDirectories: true, attributes: nil, error: &error)
swift更新之后 ,使用throws抛出异常,具体调用代码如下:
do {
try fileManager.createDirectoryAtPath(mydir1, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.description)
}
格式:
do {
try 调用函数
} catch 定义异常变量 类型 {
处理异常
}