Error
프로토콜을 준수하는 타입의 값으로 나타냄.Error
프로토콜 채택 필요enum MyError: Error {
case customError1
case customError2
}
예시를 통해 throw
, try
, do-catch
를 이해해 보자.
사용할 예시는 은행 계좌와 관련된 로직
throws
키워드 작성throw
를 사용하여 에러를 던지기.enum AccountError: Error {
case accountInactive
case insufficient
}
class BankAccount {
var balance: Double
var isActive: Bool
init(initialBalance: Double, isActive: Bool) {
self.balance = initialBalance
self.isActive = isActive
}
// 인출하는 메소드
func withdraw(amount: Double) throws {
guard isActive else {
throw AccountError.accountInactive // 던지기!
}
guard balance >= amount else {
throw AccountError.insufficient // 던지기!
}
balance -= amount
print("Withdrew \(amount). Remaining balance is \(balance).")
}
}
try
키워드를 작성해야 함.에러가 발생할 수 있지만 try해 볼게!
let myAccount = BankAccount(initialBalance: 1000, isActive: true)
do {
try myAccount.withdraw(amount: 50000)
} catch AccountError.accountInactive {
print("거래가 불가능한 계좌입니다." )
} catch AccountError.insufficient {
print("잔액이 부족합니다.")
}
// 출력: 잔액이 부족합니다.
try
/ try?
/ try!
let myAccount = BankAccount(initialBalance: 1000, isActive: true)
try myAccount.withdraw(amount: 100)
// Withdrew 100.0. Remaining balance is 900.0.
let myAccount = BankAccount(initialBalance: 1000, isActive: true)
try myAccount.withdraw(amount: 5000)
// Playground execution terminated: An error was thrown and was not caught:
에러 처리를 해 주지 않았기 때문에, 에러가 처리되지 않았다는 에러가 발생한다.
따라서 do-catch문을 사용하거나,try?
혹은 try!
를 사용해야 한다.
let myAccount = BankAccount(initialBalance: 1000, isActive: true)
try? myAccount.withdraw(amount: 5000) // nil
try! myAccount.withdraw(amount: 5000)