TIL (Today I Learned) 240201_Error Handling

Danny·2024년 2월 2일

TIL(Today I Learned)

목록 보기
26/34

2월 1일 (목)

🔥학습 내용

Error Handling

1. Error Handling이란 무엇인가?

  • Swift 가이드 문서에 따르면, 이렇게 정의한다. "Respond to and recover from errors."
    에러의 복구와 대응이다.
  • Error Handling이란 프로그램에서 에러가 발생할 조건으로부터 대응하거나 복구하는 과정이라고 볼 수 있다.

2. Representing and Throwing Errors

  • 스위프트에서는 Error 프로토콜을 채택하는 타입을 가지고 있고 있다. 보통 열거형을 사용하는 것 같다.
enum VendingMachineError: Error {
    case invalidSelection
    case insufficientFunds(coinsNeeded: Int)
    case outOfStock
}
  • throw Error를 하는 것은 정상적인 프로그램 흐름이 기대되지 않을 때, 혹은 실행이 진행되지 않을 때, 가리킨다.
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)

3. Handling Error

  • 에러를 throw할 때, Error를 핸들링 할 수 있도록 해야하는데, 그 방법이 4가지가 있다.
  1. Propagating Errors Using Throwing Functions.
  2. Handling Errors Using Do-Catch
do {
    try <#expression#>
    <#statements#>
} catch <#pattern 1#> {
    <#statements#>
} catch <#pattern 2#> where <#condition#> {
    <#statements#>
} catch <#pattern 3#>, <#pattern 4#> where <#condition#> {
    <#statements#>
} catch {
    <#statements#>
}
  1. Converting Errors to Optional Values
  2. Disabling Error Propagation

#.참고URL

profile
안녕하세요 iOS 개발자 지망생 Danny 입니다.

0개의 댓글