소피it블로그
[Swift 공식문서] The Basics 정리 (8) - Error Handling 본문
https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
The Basics — The Swift Programming Language (Swift 5.6)
The Basics Swift is a new programming language for iOS, macOS, watchOS, and tvOS app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. Swift provides its own versions of all fundamental
docs.swift.org
에러 핸들링은 실패의 이유가 무엇인지 알 수 있게 해준다.
함수는 에러 조건을 만나면 에러를 낸다. 해당 함수의 caller는 그 에러를 잡아내고 적절하게 반응할 수 있다.
func canThrowAnError() throws {
// this function may or may not throw an error
}
함수 선언시 throws 키워드를 추가해줌으로써 에러를 낼 수 있음을 알릴 수 있다. 에러를 낼 수 있는 그 함수를 부르면 해당 표현 앞에 try가 붙는다. 스위프트는 자동적으로 에러를 해당 범위 바깥으로 전달하여 catch 구문으로 넘긴다.
do {
try canThrowAnError()
// no error was thrown
} catch {
// an error was thrown
}
do 구문은 새로운 포함 범위를 만들어내는데, 이는 에러가 하나 이상의 catch 구문으로 넘겨질 수 있도록 한다.
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
위의 예시에서 makeASandwich() 함수는 깨끗한 그릇이 없거나 재료가 부족한 경우에 오류를 낼 것이다. 에러를 낼 수 있는 함수이기 때문에 함수 실행부분은 try 표현으로 감싸진다. 함수 실행부를 do 구문으로 감싸주기 때문에 에러가 난다면 catch 절로 넘어갈 것이다. 에러가 없다면 eatASandwich() 함수가 실행된다.
'개발_iOS > 스위프트' 카테고리의 다른 글
[Swift 공식문서] Functions 정리 (0) | 2022.05.15 |
---|---|
[Swift 공식문서] The Basics 정리 (9) - Assertions and Preconditions (0) | 2022.05.14 |
[Swift 공식문서] The Basics 정리 (7) - Optionals (0) | 2022.05.14 |
[Swift 공식문서] The Basics 정리 (6) - Type Aliases, Booleans, Tuples (0) | 2022.05.12 |
[Swift 공식문서] The Basics 정리 (5) - Numeric Literals, Numeric Type Conversion (0) | 2022.05.12 |