rethrows

2025. 9. 22. 13:14·Programing Langauge/swift
반응형

🥊 rethrows

 

🎯 목표

아래 상황과 같이, 클로저에서 에러를 던질 때(throw)할 때, 어떻게 던질 수 있을까?

enum CustomError: Error {
    case divideByZero
}

func divide(number: Int, divisor: Int) throws -> Int {
    if divisor == .zero {
        throw CustomError.divideByZero
    }
    
    return number / divisor
}

func calculate(function: (Int, Int) throws -> Int) {
    throw function(10, 0) // ⚠️ Thrown expression type 'Int' does not conform to 'Error'
}

try calculate(function: divide)

 

⭐️ 역할

함수 파리미터에 throws 키워드가 있고, 에러를 현재 스코프가 아닌, caller쪽에 전달하고 싶을 떄 사용

 

😀 해결

enum CustomError: Error {
    case divideByZero
}

func divide(number: Int, divisor: Int) throws -> Int {
    if divisor == .zero {
        throw CustomError.divideByZero
    }
    
    return number / divisor
}

func calculate(function: (Int, Int) throws -> Int) rethrows {
    print(try function(10, 0))
}

do {
    try calculate(function: divide)
} catch {
    print("Error: \(error)")
}

 

 

✨ 특징

  • rethrows 자리에 throws를 붙혀도 동작은 똑같다. 다만, 현재 함수에서 발생하는 erorr면 throws,
    위와 같이 파라미터로 전달된 에러일 경우는 retrhows로 표시해, 구분하는 것이 좋다고한다.
  • 부모의 throws -> 자식의 rethorws로 재정의 ✅
  • 부모의 rethrows -> 자식의 throws로 재정의 ❌
  • 프로토콜의 throws -> 구현부 rethrows ✅
  • 프로토콜의 retrhows -> 구현부 throws ❌
// MARK: - 부모 → throws
class Parent {
    func doSomething(action: () throws -> Void) throws {
        try action()
    }
}

// ✅ 자식: throws → rethrows 로 완화 (허용)
class Child: Parent {
    override func doSomething(action: () throws -> Void) rethrows {
        print("Child: safely rethrows")
        try action()
    }
}

let parent: Parent = Child()

// Parent 타입이므로 호출자는 throws 기준으로 try 필요
try parent.doSomething {
    print("Executing action") // 실제 실행은 rethrows 구현이지만 여전히 try 필요
}

// ===============================================================================================================

class Base {
    func perform(action: () throws -> Void) rethrows {
        try action()
    }
}

 ❌ 컴파일 에러: 'throws'로 강화할 수 없음

class Sub: Base {
    override func perform(action: () throws -> Void) throws {
         Error: overriding rethrows with throws is not allowed
        try action()
    }
}

// ===============================================================================================================


// MARK: - 프로토콜 rethrows
protocol ReThrowingProtocol {
    func execute(_ action: () throws -> Void) rethrows
}

// ❌ throws 로 구현하면 오류
struct WrongImpl: ReThrowingProtocol {
    func execute(_ action: () throws -> Void) throws {
        // Error: 'throws' function cannot satisfy 'rethrows' requirement
        try action()
    }
}


// ✅ 올바른 구현: rethrows 유지
struct CorrectImpl: ReThrowingProtocol {
    func execute(_ action: () throws -> Void) rethrows {
        try action()
    }
}

// ===============================================================================================================

// MARK: - 프로토콜 throws
protocol ThrowingProtocol {
    func run(_ action: () throws -> Void) throws
}

// ✅ rethrows 로 구현해도 throws 요구사항 충족
struct RethrowImpl: ThrowingProtocol {
    func run(_ action: () throws -> Void) rethrows {
        try action()
    }
}

출처

 

Swift 3.0 의 throws, rethrows 에 대하여...

반년전즈음 스터디모임에서 Swift 3.0의 Array 에 대해 다루다가 map 이라는 함수를 보고 의문점이 생겼다. 분명히 내가 기억하기로는 Swift 2.2에서 Array의 map 함수는 Array.map(transform: T -> U) 이와 같이

redsubmarine.github.io

 

반응형

'Programing Langauge > swift' 카테고리의 다른 글

@resultBuilder  (0) 2025.10.22
@autoclosure  (0) 2025.10.10
@retroactive  (0) 2025.08.23
@dynamicMemberLookup  (3) 2025.07.24
가독성 좋게 정규식 설계하기  (1) 2025.07.22
'Programing Langauge/swift' 카테고리의 다른 글
  • @resultBuilder
  • @autoclosure
  • @retroactive
  • @dynamicMemberLookup
Hamp
Hamp
남들에게 보여주기 부끄러운 잡다한 글을 적어 나가는 자칭 기술 블로그입니다.
  • Hamp
    Hamp의 분리수거함
    Hamp
  • 전체
    오늘
    어제
    • 분류 전체보기 (325) N
      • CS (30)
        • 객체지향 (2)
        • Network (7)
        • OS (6)
        • 자료구조 (1)
        • LiveStreaming (3)
        • 이미지 (1)
        • 잡다한 질문 정리 (0)
        • Hardware (2)
        • 이론 (6)
        • 컴퓨터 그래픽스 (0)
      • Firebase (3)
      • Programing Langauge (41)
        • swift (34)
        • python (6)
        • Kotlin (1)
      • iOS (133) N
        • UIKit (37)
        • Combine (1)
        • SwiftUI (33) N
        • Framework (7)
        • Swift Concurrency (22)
        • Tuist (6)
        • Setting (11)
        • Modularization (1)
        • Instruments (6)
      • PS (59)
        • 프로그래머스 (24)
        • 백준 (13)
        • LeetCode (19)
        • 알고리즘 (3)
      • Git (18)
        • 명령어 (4)
        • 이론 (2)
        • hooks (1)
        • config (2)
        • action (7)
      • Shell Script (2)
      • Linux (6)
        • 명령어 (5)
      • Spring (20)
        • 어노테이션 (6)
        • 튜토리얼 (13)
      • CI-CD (4)
      • Android (0)
        • Jetpack Compose (0)
      • AI (9)
        • 이론 (9)
        • MCP (0)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    IOS
    AVFoundation
    백준
    UIKit
    Tuist
    dp
    투포인터
    Swift
    concurrency
    boostcamp
    property
    프로그래머스
    SwiftUI
    dfs
    CS
    Spring
    GIT
    protocol
    dispatch
    lifecycle
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.0
Hamp
rethrows
상단으로

티스토리툴바