3.10
Error Handling
假设某个函数myFunction需要去返回一个String类型,不过有可能会在某个点抛出异常,一般来说会将该函数的返回值设置为String?:
Example:
func readFile(withFilename filename: String) -> String? {
guard let file = openFile(filename)else{
return nil
}
let fileContents = file.read()
file.close()
return fileContents
}
func printSomeFile() {
let filename = "somefile.txt"
guard let fileContents = readFile(filename)else{
print("Unable to open file \(filename).")
return
}
print(fileContents)
}
不过作为异常处理的角度,我们应该使用Swift的try-catch表达式,这样能显式地知道错误点:
struct Error: ErrorType {
public let file: StaticString
public let function: StaticString
public let line: UInt
public let message: String
public init(message: String, file: StaticString = #file, function: StaticString = #function, line: UInt = #line) {
self.file = file
self.function=function
self.line = line
self.message = message
}
}
Example usage:
func readFile(withFilename filename: String) throws -> String {
guard let file = openFile(filename)else{
throwError(message: "Unable to open file named \(filename).")
}
let fileContents = file.read()
file.close()
return fileContents
}
func printSomeFile() {
do{
let fileContents =tryreadFile(filename)
print(fileContents)
}catch{
print(error)
}
}
总而言之,如果某个函数可能会出错,并且出错的原因不能显式地观测到,那么应该优先抛出异常而不是使用一个Optional作为返回值。