Python 예외처리
2022. 12. 16. 15:57ㆍPython
people = [
{'name': 'bob', 'age': 20},
{'name': 'carry', 'age': 38},
{'name': 'john', 'age': 7},
{'name': 'smith', 'age': 17},
{'name': 'ben', 'age': 27},
{'name': 'bobby'},
{'name': 'red', 'age': 32},
{'name': 'queen', 'age': 25}
]
for person in people:
if person['age'] > 20:
print(person['name'])
# bobby의 age가 없으므로 아래와 같은 에러가 발생한다.
# carry
# ben
# if person['age'] > 20:
# KeyError: 'age'
for person in people:
try:
if person['age'] > 20:
print(person['name'])
except:
print(person['name'], 'error!')
# carry
# ben
# bobby error!
# red
# queen
예외처리가 늘 그렇듯, 필요한 부분이 아니면 최대한 자제하여 사용할 것.
어디서 에러가 나는지 모르는 상황이 발생할 수 있다.
'Python' 카테고리의 다른 글
Python 함수(1) (0) | 2022.12.15 |
---|---|
Python While반복문 (0) | 2022.12.15 |
Python for반복문 (0) | 2022.12.15 |