파이썬에는 Exception 클래스가 있으며, 이 클래스는 StopIteration, StandardError, Warning의 기본(base) 클래스입니다. 모든 표준 오류는 StandardError에서 파생됩니다. ArithmeticError, AttributeError, AssertionError와 같은 대표적인 표준 오류들 역시 기본 클래스인 StandardError로부터 상속받습니다.
객체의 속성(attribute) 참조나 할당이 실패하면 AttributeError가 발생합니다. 가장 흔한 경우는 존재하지 않는 속성을 참조하려고 시도할 때입니다.
아래 예제에서는 try-except 블록으로 예외를 잡아(catch) 어떤 오류 메시지가 출력되는지, 그리고 발생한 예외의 유형이 무엇인지 확인해 보겠습니다.
예제
import sys
try:
class Foobar:
def __init__(self):
self.p = 0
f = Foobar()
print f.p
print f.q
except Exception as e:
print e
print sys.exc_type
print 'This is an example of StandardError exception'출력
0 Foobar instance has no attribute 'q' <type 'exceptions.AttributeError'> This is an example of StandardError exception
참고: Python 2와 Python 3의 차이
위 코드는 Python 2 기준으로 작성되었습니다. StandardError는 Python 2에만 존재하는 클래스이며, Python 3에서는 제거되었습니다. Python 3에서는 모든 내장 예외가 곧바로 Exception 클래스를 상속하므로, 동일한 목적이라면 except Exception 구문을 그대로 사용하면 됩니다. 또한 Python 3 환경에서는 print 문 대신 print() 함수를 사용하고, sys.exc_type 대신 type(e)로 예외 유형을 확인하는 것이 권장됩니다.