개발/Python
Python 예외처리
LukeHan1128
2020. 11. 15. 17:11
반응형
참고
# try-except 문
def safe_pop_print(list, index):
try:
print(list.pop(index))
except IndexError:
print('{} index의 값을 가져올 수 없습니다.'.format(index))
safe_pop_print([1,2,3], 5) # 5 index의 값을 가져올 수 없습니다.
# if 문
def safe_pop_print(list, index):
if index < len(list):
print(list.pop(index))
else:
print('{} index의 값을 가져올 수 없습니다.'.format(index))
safe_pop_print([1,2,3], 5) # 5 index의 값을 가져올 수 없습니다.
# 모든 에러 처리
try:
list = []
print(list[0]) # 에러가 발생할 가능성이 있는 코드
text = 'abc'
number = int(text)
except:
print('에러발생')
# 에러 이름 확인
try:
list = []
print(list[0]) # 에러가 발생할 가능성이 있는 코드
except Exception as ex: # 에러 종류
print('에러가 발생 했습니다', ex) # ex는 발생한 에러의 이름을 받아오는 변수
# 에러가 발생 했습니다 list index out of range
# 올바른 값을 넣지 않으면 에러를 발생시키고 적당한 문구를 표시한다.
def rsp(mine, yours):
allowed = ['가위','바위', '보']
if mine not in allowed:
raise ValueError
if yours not in allowed:
raise ValueError
try:
rsp('가위', '바')
except ValueError:
print('잘못된 값을 넣었습니다!')
반응형