contents
<aside> 🧨 프로그램 내에서 에러가 발생한 상황에 대해 대응하고 이를 복구하는 과정
</aside>
Q. 에러는 무엇인가?
A. Error 프로토콜을 따르는 타입의 값
Q. 예외 처리 왜 필요한가?
A. optional타입은 오류가 발생했을 때 오류에 대한 정보를 외부로 전달할 방법이 없다. 따라서 예외 처리를 통해서 오류를 처리하자!
에러 처리를 하기 위해선 세 가지 과정이 필요합니다.
오류의 종류 정의하기(옵션)
enum NetworkError: Error {
case authErr
case pathErr
case serverErr
}
enum TestError: Error {
case notANumber
case invalidInput(testNum: Int)
}
발생한 오류 던지기
throws
를 이용해 오류를 처리해주는 곳으로 던집니다.
private func calculateRate(watched: Int, total: Int) -> Double {
guard total != 0 else { return 0 }
let result = Double(watched) / Double(total)
return result
}///inf
guard문을 이용해서 total이 0이 되면서 일어날 수 있는 오류를 해결하고 있습니다.
✅ throw를 사용해서 오류를 던져주자
throw
는 총 두 군데에 써주시면 됩니다.
throws
를 오류가 발생할 가능성이 있는 메소드 제목 옆에 써줍니다.throw
를 오류가 발생할 구간에 써줍니다.private func calculateRate(watched: Int, total: Int) throws -> Double {
guard total != 0 else { throw TestError.notANumber }
let result = Double(watched) / Double(total)
return result
}
변수를 받는 케이스의 경우에는,
private func calculateRate(watched: Int, total: Int) throws -> Double {
guard total > 0 else { throw TestError.invalidInput(testNum: number) }
let result = Double(watched) / Double(total)
return result
}
던진 오류 처리하기
try와 do-catch로 오류를 처리합니다.
class Rate {
private func calculateRate(watched: Int, total: Int) throws -> Double {
guard total != 0 else { throw TestError.notANumber }
let result = Double(watched) / Double(total)
return result
}
}
class AnotherClass {
private func test() {
let rate = try Rate().calculateRate(watched: 10, total: 0)
}
}
오류를 발생시키는 메소드 앞에 try
를 넣어줍니다.
try
: calculateRate가 오류를 발생시킬 수도 있지만, 한 번 시도해보겠다.
do-catch
문을 사용해서 오류를 처리해준다.
do-catch
는 오류를 처리하는 가장 간단한 방법이다.switch문
으로도 쓸 수 있습니다.do {
let rate = try Rate().calculateRate(watched: 10, total: 0)
} catch {
print(error)
}
class AnotherClass {
private func test() {
do {
let rate = try Rate().calculateRate(watched: 10, total: 0)
} catch TestError.notANumber {
print("0를 넣으면 inf가 생성됩니다.. 에러!")
} catch TestError.invalidInput(let testNumber) {
print("부적절한 숫자를 넣었습니다. \\(testNumber)")
}
}
}
enum TestError: Error, String {
case notANumber = "0를 넣으면 inf가 생성됩니다.. 에러!"
case invalidInput = "부적절한 숫자를 넣었습니다."
}
class AnotherClass {
private func test() {
do {
let rate = try Rate().calculateRate(watched: 10, total: 0)
} catch {
switch error {
case TestError.notANumber:
print(error.rawValue)
case TestError.invalidInput:
print(error.rawValue)
}
}
}
}
기본적으로 사용하는 try
는 성공하는 경우에 unwrapping된 값을 반환받게 됩니다.