enum ErrorCode: Error { case divideZero case none var str: String { switch self { case .divideZero: return "divided by zero" default: return "not defined" } } } //예외를 던지는 함수는 throws 표기 func divide(_ a: Double, _ b: Double) throws -> Double { if b == 0.0 { throw ErrorCode.divideZero } return a/b } extension Int { //예외를 던지는 함수를 호출하고 do-try-catch 하지 않으면 rethrows 로 예외 던짐 func divide(_ a: Int, fn: (Double, Double) throws -> Double) rethrows -> Int { try Int(fn(Double(self), Double(a))) } }
func something() { var ret = -1 defer { print("divide result \(ret)") } do { ret = try 10.divide(0, fn: divide(_:_:)) } catch let err { print("\((err as? ErrorCode)?.str ?? "")") } }