Test/Python(20220101~)

Days30.1 Error Handling Exercise

kiostory 2022. 9. 18. 12:31

[IndexError]

fruits 리스트 내의 범위를 벗어나는

인덱스 에러가 발생하면,

 

인덱스 에러 대신에

디폴트 값인 'Fruit pie' 를 출력할 수 있도록 코딩.

 

fruits = ["Apple", "Pear", "Orange"]

#TODO: Catch the exception and make sure the code runs without crashing.
def make_pie(index):
    try:
        fruit = fruits[index]
    except IndexError:
        print("Fruit pie")
    else:
        print(fruit + " pie")

make_pie(int(input("Number(0-2): ")))

 

 

[KeyError]

딕셔너리에서 Likes 키가 없는 리스트가 있기 때문에 

아래 코딩은 실행 에러가 발생한다.

facebook_posts = [
    {'Likes': 21, 'Comments': 2}, 
    {'Likes': 13, 'Comments': 2, 'Shares': 1}, 
    {'Likes': 33, 'Comments': 8, 'Shares': 3}, 
    {'Comments': 4, 'Shares': 2}, 
    {'Comments': 1, 'Shares': 1}, 
    {'Likes': 19, 'Comments': 3}
]

total_likes = 0

for post in facebook_posts:
    total_likes = total_likes + post['Likes']


print(total_likes)

 

실행에러:

C:\Users\kiost\PycharmProjects\pythonProject\Days30.2.ErrorHandling\venv\Scripts\python.exe C:/Users/kiost/PycharmProjects/pythonProject/Days30.2.ErrorHandling/main.py
Traceback (most recent call last):
  File "C:\Users\kiost\PycharmProjects\pythonProject\Days30.2.ErrorHandling\main.py", line 13, in <module>
    total_likes = total_likes + post['Likes']
KeyError: 'Likes'

 

 

try로 확인하고, except를 통해 예외처리 

facebook_posts = [
    {'Likes': 21, 'Comments': 2},
    {'Likes': 13, 'Comments': 2, 'Shares': 1},
    {'Likes': 33, 'Comments': 8, 'Shares': 3},
    {'Comments': 4, 'Shares': 2},
    {'Comments': 1, 'Shares': 1},
    {'Likes': 19, 'Comments': 3}
]

total_likes = 0

for post in facebook_posts:
  try:
    total_likes += post['Likes']
  except KeyError:
    pass

print(total_likes)

실행결과 : 

86