Test/Python(20220101~)

Days30. 예외 포착하고 다루기(try,except,else,finally)

kiostory 2022. 9. 14. 20:59
# #FileNotFoundError : [Errno 2] No such file or directory: 'a_file.txt'
# with open("a_file.txt")as file:
#     file.read()

# #KeyError : 'not_existent_key'
# a_dictionary={"key":"value"}
# value=a_dictionary["not_existent_key"]

# #IndexError : list index out of range
# fruit_list = ["Apple","Banana","Pear"]
# fruit = fruit_list[3]
# print(fruit)

# #TypeError : can only concatenate str (not "int") to str
# text = "abc"
# print(text+5)

## 우리가 예외를 다룰 떄의 코드 모습
#try:
#   something that might cause an exception
#except:
#   do this if there was an exception 
#else:
#   do this if there were no exception
#finally:
#   do this no matter what happens
#------------------------------------------------------------------------------



try:
    file = open("a_file.txt")
    a_dictionary={"key":"value"}
    print(a_dictionary["key"])
except FileNotFoundError:
    #except: #bare exception을 쓰지 마라. 실제 에러가 발생해도 아무 정보도 표출하지 않을 수 있다
    #print("a_file.txt가 없으므로 만듭니다.")
    file = open("a_file.txt","w")
    file.write("Something")
except KeyError as error_message:  #에러 메세지를 잡아 사용할 수도 있다.
    #except KeyError:
    print(f"The key {error_message} does not exist.")
else:
    content=file.read()
    print(content)
finally:
    file.close()
    print("File was closed.")



-----------------------------------------------------------------------------------
실행결과
value
Something
File was closed.

Process finished with exit code 0