Error 프로토콜을 따르는 열거형 선언
enum FileTransferError: Error {
case noConnection
case lowBandwidth
case fileNotFound
}
func transferFile() throws -> Bool { }
let connectionOK = true
let connectionSpeed = 30.00
let fileFound = false
enum FileTransferError: Error {
case noConnection
case lowBandwidth
case fileNotFound
}
func fileTransfer() throws {
guard connectionOK else {
throw FileTransferError.noConnection
}
guard connectionSpeed > 30 else {
throw FileTransferError.lowBandwidth
}
guard fileFound else {
throw FileTransferError.fileNotFound
}
}
메서드 내에 있는 각각의 guard 구문은 각 조건이 참인지 거짓인지를 검사한다. 만약 거짓이라면 throw 구문을 사용하여 FileTransferError 열거형에 있는 에러 값들 중 하나를 던진다.
do-catch 구문 사용
func sendFile() -> String {
do {
try fileTransfer()
} catch FileTransferError.noConnection {
return "No Network Connection"
} catch FileTransferError.lowBandwidth {
return "File Transfer Speed too Low"
} catch FileTransferError.fileNotFound {
return "File not Found"
} catch {
return "Unknown error"
}
return "Successful transfer"
}
do {
try filemgr.createDirectory(atPath: newDir, withIntermediateDirectories: true, attributes: nil)
} catch let error {
print("Error: \(error.localizedDescription)")
}
try! 구문을 사용하면 do-catch 구문 내에서 메서드가 호출되도록 감싸지 않아도 스로잉 메서드가 강제로 실행된다.
try! fileTransfer
defer 구문은 메서드가 결과를 반환하기 직전에 실행되어야 하는 일련의 코드를 지정할 수 있게 해준다.
func sendFile() -> String {
defer {
removeTmpFiles()
closeConnection()
}
do {
try fileTransfer()
} catch FileTransferError.noConnection {
return "No Network Connection"
} catch FileTransferError.lowBandwidth {
return "File Transfer Speed too Low"
} catch FileTransferError.fileNotFound {
return "File not Found"
} catch {
return "Unknown error"
}
return "Successful transfer"
}