아래 사용한 예제들은 모두 swift 공식문서 예제를 그대로 가져오거나 약간 활용한 것이다.
출처: https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html
Error Handling — The Swift Programming Language (Swift 5.6)
Error Handling Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime. Some operations aren
docs.swift.org
에러 던지기 (throw) & throws 키워드를 가지는 메소드
nil 때문에 앱이 꺼져버리는 것 말고도 프로그램 실행 중에 의도적으로 에러를 발생시켜서 에러에 따라 어떻게 처리할 지 정해둬야 할 때가 있다. 공식 문서에 나온 예를 보면,
enum VendingMachineError: Error {
case invalidSelection
case insufficientFunds(coinsNeeded: Int)
case outOfStock
}
Error 프로토콜을 채택하는 enum 타입으로 에러를 정의한다. 그리고 필요한 곳에서 throw 키워드를 사용하여 이 에러 중에 하나를 던지면 된다.
class VendingMachine {
var sodaStock: Int = 100
func getOneItem(coin: Int) throws {
if coin == 5 {
print("here is your soda")
} else {
throw VendingMachineError.insufficientFunds(coinsNeeded: 5)
}
}
}
대충 클래스 하나를 만들었다. 정수 타입의 parameter를 가지는 getOneItem 메소드가 있고 parameter가 5가 아니면 throw 키워드 다음에 위에 enum 타입으로 작성한 에러 중에 하나를 던진다. 메소드 선언부에 있는 'throws' 키워드가 있어야 그 메소드 내부에서 throw를 사용하여 에러를 던질 수 있다.
do .. try ... catch 문
위처럼 throws 키워드가 있는 메소드를 호출할 때는 혹시나 던져질 수 있는 에러를 처리할 수 있는 do catch 문을 사용해야 한다.
do {
try 어떤메소드()
// 위에서 던져진 에러가 없으면 다음줄로 계속 실행된다.
} catch 어떤에러1 {
// 만약 do 에서 에러가 발생하면, 각 catch에서 다루는 에러에 맞는 곳으로 간다
} catch 어떤에러2 {
} catch let error as NSError {
}
그래서 이렇게 do catch를 사용해서 위에서 던진 에러를 잡으려면...
let vmOne = VendingMachine()
do {
try vmOne.getOneItem(coin: 3)
print("I got soda!")
} catch VendingMachineError.outOfStock {
print("oops out of stock")
} catch VendingMachineError.invalidSelection {
print("wrong item")
} catch VendingMachineError.insufficientFunds(let coinNum) {
print("\(coinNum) is needed")
}
맨 위에서 만든 enum을 사용하여 각 에러에 따라 처리할 수 있겠다.
'swift & iOS > swift' 카테고리의 다른 글
[swift] 프로토콜 protocol (0) | 2022.01.31 |
---|---|
[swift] 제네릭 generic <> (0) | 2022.01.28 |
[swift] 옵셔널 체이닝 optional chaining (0) | 2022.01.28 |
[swift] 열거형 (enum with associated value)과 옵셔널 optional (0) | 2022.01.27 |
[swift] 함수의 inout 파라미터 (0) | 2022.01.27 |