티스토리 뷰

# #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

 

'Test > Python(20220101~)' 카테고리의 다른 글

Days30.1 Error Handling Exercise  (0) 2022.09.18
나만의 예외, raise  (0) 2022.09.18
Days29. 웹싸이트 패스워드 관리  (0) 2022.09.12
1차 2급 연습1  (0) 2022.06.06
Days29. Password manager - 2  (0) 2022.05.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함