반응형
# 아래 try 구문 안에 에러가 발생하게 되면 따로 처리할 수 있게 하기 위한 try 단락
try:
file = open("test.txt")
test_dict = {"key" : "value"}
print(text_dict["test"])
# try 구문 안에 File을 못 찾는 에러 발생시 호출
except FileNotFoundError:
print("File Not Found. You need to create File")
# try 구문 안에 dictionary key를 못찾는 에러 발생시 호출
except KeyError as error_message:
print(f"The Key {error_message} Find Error")
# 에러가 없이 정상 동작한 경우 호출
else:
content = file.read()
print(content)
# 에러가 있든 없든 실행하는 단락
finally:
file.close()
print("File Close")
# raise 구문을 알아보자. 특정 상태일 때 유저가 에러를 강제로 발생시키는 구문으로서 아래처럼 사용
test_val = int(input("Distance : ")
if test_val > 10
raise ValueError("Need to Distance value is lower than 10")
print(test_val)
기존의 C계열 언어들에도 있는 예외처리 기능으로 파이썬에서 문법이 어떻게 되는 지 정도 간단히 정리해두었다
반응형
'Devs > Python' 카테고리의 다른 글
[Python] datetime 사용법 (0) | 2025.04.09 |
---|---|
[Python] json 사용 방법 (0) | 2025.04.07 |
[Python] Pyperclip 사용법 - 클립보드로 간편히 복사 기능 (0) | 2025.04.05 |
[Python] Tkinter - Message Box (0) | 2025.04.05 |
[Python] Tkinter - Canvas Widget (0) | 2025.04.04 |