🔥 커스텀 예외 만들기
Python에서 예외(exception)는 일반적인 흐름을 방해하는 이벤트를 의미합니다. 때로는 기본 제공되는 예외로 충분하지 않을 때가 있습니다. 이럴 때 사용자 정의 예외(User-Defined Exceptions)를 만들어 사용하는 것이 좋습니다. 커스텀 예외를 만드는 것은 프로그램을 더 안전하고 유지보수하기 쉽게 만들어줍니다.
커스텀 예외의 필요성
커스텀 예외를 사용하면 특정 에러 상황을 더 명확하게 표현할 수 있습니다. 또한, 예외의 이름만 보고도 에러의 원인을 쉽게 파악할 수 있어 코드의 가독성이 향상됩니다.
class NetworkError(Exception):
pass
class DatabaseError(Exception):
pass
class NetworkError(Exception):
pass
class DatabaseError(Exception):
pass
기본 예외 클래스 상속
커스텀 예외를 만들 때는 기본 Exception 클래스를 상속받아야 합니다. 이렇게 하면 모든 예외의 기본적인 기능을 유지하면서 필요한 부분만 추가할 수 있습니다.
class MyError(Exception):
pass
class MyError(Exception):
pass
예외 메시지 추가
예외에 메시지를 추가하면 에러 상황을 더 자세히 설명할 수 있습니다. __init__ 메서드를 오버라이딩하여 구현할 수 있습니다.
class ValidationError(Exception):
def __init__(self, message):
self.message = message
class ValidationError(Exception):
def __init__(self, message):
self.message = message
추가 데이터 포함
예외에 추가 데이터를 포함시켜 더 많은 정보를 제공할 수 있습니다. 이를 통해 에러 처리를 더 유연하게 할 수 있습니다.
class APIError(Exception):
def __init__(self, status_code, message):
self.status_code = status_code
self.message = message
class APIError(Exception):
def __init__(self, status_code, message):
self.status_code = status_code
self.message = message
예외 처리 패턴
커스텀 예외를 만든 후에는 try-except 블록으로 적절히 처리해야 합니다. 이를 통해 예외 상황을 보다 효과적으로 관리할 수 있습니다.
try:
raise ValidationError("Invalid input")
except ValidationError as e:
print(f"Error: {e.message}")
try:
raise ValidationError("Invalid input")
except ValidationError as e:
print(f"Error: {e.message}")
예외 체이닝
예외 체이닝은 한 예외가 다른 예외를 발생시킬 때 유용합니다. from 키워드를 사용하여 예외 간의 관계를 명확히 할 수 있습니다.
try:
raise KeyError("Key is missing")
except KeyError as e:
raise ValueError("Invalid key") from e
try:
raise KeyError("Key is missing")
except KeyError as e:
raise ValueError("Invalid key") from e
커스텀 예외의 활용 사례
실제 프로젝트에서 커스텀 예외를 어떻게 활용할 수 있는지 사례를 통해 살펴봅니다.
class FileNotExistsError(Exception):
def __init__(self, file_path):
self.file_path = file_path
self.message = f"{file_path} does not exist"
super().__init__(self.message)
# 파일 처리 예시
try:
file
_path = "unknown_file.txt"
if not os.path.exists(file_path):
raise FileNotExistsError(file_path)
except FileNotExistsError as e:
print(e.message)
class FileNotExistsError(Exception):
def __init__(self, file_path):
self.file_path = file_path
self.message = f"{file_path} does not exist"
super().__init__(self.message)
# 파일 처리 예시
try:
file
_path = "unknown_file.txt"
if not os.path.exists(file_path):
raise FileNotExistsError(file_path)
except FileNotExistsError as e:
print(e.message)
연습문제
TemperatureTooHigh와TemperatureTooLow라는 두 개의 커스텀 예외 클래스를 만드세요.- 사용자로부터 온도를 입력받아, 설정된 범위를 벗어나면 해당 예외를 발생시키는 함수를 작성하세요.
try-except블록을 사용하여 이 예외들을 적절히 처리하는 코드를 작성하세요.











