[udemy] python 부트캠프_section 30_try,except,else,finally

Dreamer ·2022년 9월 12일
0
post-thumbnail

01. try, except, else, finally

  • try : Something that might cause an exception
  • except : Do this if there was an exception
  • else : Do this if there was no exception
  • finally : Do this no matter what happens
try:
    file = open("a_file.txt") # first error
    a_dictionary = {"key": "value"} 
    print(a_dictionary["non_existent_key"]) # second error

except FileNotFoundError:
   file= open("a_file.txt","w")
   file.write("Something")

except KeyError as error_message:
    print(f"The key {error_message} does not exist.")

else:
    content = file.read()
    print(content)

finally:
    file.close()
    print("file was closed!")
  • try 구문에서 첫 번째 에러가 발생된 후, except FileNotFoundError 구문이 실행됨,
  • 다시 "run"을 하게 되면 try 구문에서 두 번째 에러가 발생된 후, except KeyError가 실행됨.
  • 모든 error가 사라져야 else 구문이 실행됨.
  • finally 구문은 항상 실행됨.
height = float(input("Height: "))
weight = int(input("Weight: "))

if height > 3:
    raise ValueError("Human Height should not be over 3 meters.")

bmi = weight / height ** 2
print(bmi)
  • raise: 나만의 error를 생성 가능! 코드 상으론 문제 없이 돌아가도 위의 예와 같이 발생할 수 있는 오류를 raise를 통해 잡아낼 수 있음.

02. Quiz

  • IndexError handling
fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
  try:
    fruit = fruits[index]
    print(fruit + " pie")
  except IndexError:
    print("There is no index exist in list.")
  else:
    print(fruit+"pie")
  
make_pie(4)

03. Quiz

  • KeyError handling
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 = total_likes + post['Likes']
  except KeyError:
    pass # or total_likes += 0 

print(total_likes)

04. Quiz

import pandas as pd

data = pd.read_csv("nato_phonetic_alphabet.csv")
phonetic_dict = {row.letter:row.code for (index, row) in data.iterrows()}

def generate_phonetic():
    word = input("Enter a word: ").upper()
    try:
        output_list = [phonetic_dict[letter] for letter in word]

    except KeyError:
        print("Sorry, only letters in the alphabet please.")
        generate_phonetic()
    else:
        print(output_list)

generate_phonetic()
profile
To be a changer who can overturn world

1개의 댓글

comment-user-thumbnail
2023년 2월 28일

I'm Ruhi and I'm managing the https://www.adelhiescort.com/location/noida-escorts.html Organization near Entryway of Indian Lodgings, Consistently the clients interest for the free transport of the females who are working in my association.

답글 달기