Devs/Python

[Python] try, catch, except, finally, raise 사용법

whawoo 2025. 4. 7. 19:10
반응형
# 아래 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계열 언어들에도 있는 예외처리 기능으로 파이썬에서 문법이 어떻게 되는 지 정도 간단히 정리해두었다

반응형