Week2-5. exception(예외)
#예제:ZeroDivisionError
def div(num1,num2):
print('Division : {}'.format(num1 / num2))
num1 = int(input('Number1 : '))
num2 = 0
div(num1,num2) #어떤 수를 0으로 나눌 수 없기 때문에 'ZeroDivisionError: division by zero'예외 발생
#예제:IndexError(list에서 index오류 등)
list = ['a','b','c','d','e'] #요소값이 5개이므로 index는 0~4이다.
print(list[5]) #요소값이 5개로 index는 0~4사이 값을 가지므로 index 5인 요소값을 존재하지 않아 IndexError: list index out of range 예외가 발생한다.
#예제: 사용자로부터 숫자를 입력받아 int_casting하고, 짝수,홀수 여부를 출력하는 코드, 예외발생 여부와 상관없이 사용자가 입력한 data를 항상 출력하는 코드
----------------------------------------------------------------------
try:
실행코드
except:
예외가 발생했을 때 실행할 코드
else:
예외가 발생하지 않을 때 실행할 코드
finally:
예외 발생 여부와 상관없이 실행 할 코드
----------------------------------------------------------------------
try:
userData = input('Number : ')
userDataInt = int(userData) #문자열이 입력된 경우 int_casting에서 예외 발생
except:
print('Exception occurs.')
else:
if userDataInt % 2 == 0:
print('It is even number.')
else:
print('It is odd number.')
finally:
print('User\'s input : {}'.format(userData))
#예제: 다음과 같은 은행 계좌 개설 및 입/출금 프로그램 코드
----------------------------------------------------------------------
bank.py
import random
class PrivateBank:
def __init__(self,bank):
self.bank = bank
self.name = input('Name : ')
while True:
newAccount = random.randint(10000,99999) #새로운 계좌번호 생성
if bank.existingAccount(newAccount): #계좌번호 중복 확인
continue
else:
self.account = newAccount
break
self.total = 0
bank.addAccount(self) #bank에 self 등록
def printPrivateBankInfo(self):
print('-'*30)
print('Name : {}'.format(self.name))
print('Account : {}'.format(self.account))
print('Total : {}'.format(self.total))
print('-' * 30)
class Bank:
def __init__(self):
self.accounts = {} #dictionary를 속성으로 갖는 객체 생성 가능
def addAccount(self,privateBank):
self.accounts[privateBank.account] = privateBank #key:account, value:privateBank
def existingAccount(self,account):
return account in self.accounts
def deposit(self,account,money):
privateBank = self.accounts[account]
privateBank.total = privateBank.total + money
def withdraw(self,account,money):
privateBank = self.accounts[account]
if privateBank.total - money < 0:
raise LackException(privateBank.total,money) #raise: 예외를 발생시키는 키워드로, 프로그램이 의도하지 않은 방향으로 실행되는 것을 방지하기 위해서 에러를 발생시킨다.
privateBank.total = privateBank.total - money
class LackException(Exception):
def __init__(self,money1, money2):
super().__init__('Lack of deposit(Deposit : {} \t Withdraw : {}'.format(money1,money2))
----------------------------------------------------------------------
import bank
shinhan = bank.Bank() #accounts_dictionary를 속성으로 가지는 객체
myAccount = bank.PrivateBank(shinhan)
myAccount.printPrivateBankInfo()
while True:
mode = int(input('1.Deposit \t 2.Withdraw \t 3.Finish '))
if mode == 1:
money = int(input('Deposit money : '))
shinhan.deposit(myAccount.account,money)
myAccount.printPrivateBankInfo()
elif mode == 2:
money = int(input('Withdraw : '))
try:
shinhan.withdraw(myAccount.account,money)
myAccount.printPrivateBankInfo()
except bank.LackException as e:
print(e)
elif mode == 3:
print('Finish')
break
else:
print('Wrong access.')