본문 바로가기
카테고리 없음

파이썬 'TypeError: exceptions must be old-style classes or derived from BaseException, not type'

by 왕 달팽이 2020. 2. 15.
반응형

파이썬 프로그램을 작성하다가 다음 에러를 만나게 되었다.

TypeError: exceptions must be old-style classes or derived from BaseException, not type

try-except 구문을 이용해서 예외처리를 해놓은 부분에서 이런 에러가 발생했다. 이 TypeError는 raise 키워드를 이용해서 예외를 발생시킬 때 사용하는 클래스는 'old-style' 클래스이거나 BaseException 클래스를 상속한 클래스여야한다는 의미다.

문제가 있었던 코드는 다음과 같다.

class UserDefinedException(object):
    pass

try:
    # ... Do Something
except OSError:
    raise UserDefinedException

try-except 구문을 이용해 OSError를 받아 UserDefinedException으로 다시 던지는 코드다. UserDefinedException 클래스는 IDE에서 제공하는 클래스 자동생성 기능을 이용해 만들었다.

해결방안

TypeError를 해결하기 위해서는 Exception 정의를 조금만 바꿔주면 된다.

class UserDefinedException(Exception):
    pass

Object 클래스가 아닌 Exception 클래스를 상속해서 정의하면 정상적으로 Exception이 raise 되고 예상한대로 동작한다.

예외에 메시지 담아 던지기

추가로 예외를 만들어 raise 키워드를 이용해 상위 코드로 던질 때, 에러 상황에 대한 내용을 메시지로 담아서 던지고 싶을 때가 있다. 이럴 때는 다음과 같이 Exception 클래스를 정의하면 된다.

class UserDefinedException(Exception):
    def __init__(self, message):
        self.message = message
    
    def __str__(self):
        return self.message

이 예외를 raise 할 때는 다음과 같이 사용하면 된다.

raise UserDefinedException("ERROR: Exception")

이 예외를 처리할 상위 코드에서는 다음과 같이 처리해주면 된다. 

try:
    # Do Something..
except UserDefinedException as e:
    print(e)

이렇게 해주면 try 블럭에서 발생한 UserDefinedException을 except 절에서 잡아 에러 메시지를 출력할 수 있다.

반응형

댓글