Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬(Python) 예외 기본 클래스 완벽 가이드

다른 고급 프로그래밍 언어와 마찬가지로 파이썬에도 다양한 예외(Exception)가 존재합니다. 코드 실행 중 문제가 발생하면 파이썬은 자동으로 예외를 발생(raise)시키며, 대표적으로 ZeroDivisionError(0으로 나누기 오류), AssertionError(단정문 실패 오류) 등이 있습니다.

모든 예외 클래스는 최상위 클래스인 BaseException에서 파생됩니다. 파이썬은 내장 예외를 제공하며, 개발자가 코드에서 직접 예외를 발생시키는 것도 가능합니다. 또한 사용자는 Exception 클래스 또는 그 하위 클래스를 상속받아 자신만의 사용자 정의 예외를 만들 수 있습니다.

BaseException과 Exception의 차이

BaseException은 모든 예외의 뿌리가 되는 기본 클래스입니다. 다만 사용자 정의 예외 클래스는 이 클래스를 직접 상속해서는 안 되며, 반드시 Exception 클래스를 상속받아 작성해야 합니다. 그 이유는 SystemExit, KeyboardInterrupt처럼 프로그램 종료와 관련된 예외까지 함께 잡아버리는 것을 방지하기 위함입니다.

파이썬 예외 계층 구조

파이썬의 주요 예외들은 아래와 같은 계층 구조로 구성되어 있습니다.

  • BaseException
    • Exception
      • ArithmeticError
        • FloatingPointError
        • OverflowError
        • ZeroDivisionError
      • AssertionError
      • AttributeError
      • BufferError
      • EOFError
      • ImportError
        • ModuleNotFoundError
      • LookupError
        • IndexError
        • KeyError
      • MemoryError
      • NameError
        • UnboundLocalError
      • OSError
        • BlockingIOError
        • ChildProcessError
        • ConnectionError
          • BrokenPipeError
          • ConnectionAbortedError
          • ConnectionRefusedError
          • ConnectionResetError
        • FileExistsError
        • FileNotFoundError
        • InterruptedError
        • IsADirectoryError
        • NotADirectoryError
        • PermissionError
        • ProcessLookupError
        • TimeoutError
      • ReferenceError
      • RuntimeError
        • NotImplementedError
        • RecursionError
      • StopIteration
      • StopAsyncIteration
      • SyntaxError
        • IndentationError
          • TabError
      • SystemError
      • TypeError
      • ValueError
        • UnicodeError
          • UnicodeDecodeError
          • UnicodeEncodeError
          • UnicodeTranslateError
      • Warning
        • BytesWarning
        • DeprecationWarning
        • FutureWarning
        • ImportWarning
        • PendingDeprecationWarning
        • ResourceWarning
        • RuntimeWarning
        • SyntaxWarning
        • UnicodeWarning
        • UserWarning
    • GeneratorExit
    • KeyboardInterrupt
    • SystemExit

사용자 정의 예외 실습 예제

문제 상황: 직원(Employee)을 나타내는 클래스가 있고, 직원의 나이는 반드시 18세보다 커야 한다는 조건이 있다고 가정해 보겠습니다.

이 조건을 위반했을 때 발생시킬 수 있도록, Exception 클래스를 상속받는 사용자 정의 예외 클래스를 하나 만들어야 합니다.

예제 코드

class LowAgeError(Exception):
    def __init__(self):
        pass

    def __str__(self):
        return '나이는 반드시 18세보다 커야 합니다'

class Employee:
    def __init__(self, name, age):
        self.name = name
        if age < 18:
            raise LowAgeError
        else:
            self.age = age

    def display(self):
        print('직원 이름: ' + self.name + ', 나이: ' + str(self.age) + '세')

try:
    e1 = Employee('Subhas', 25)
    e1.display()

    e2 = Employee('Anupam', 12)
    e2.display()
except LowAgeError as e:
    print('오류 발생: ' + str(e))

실행 결과

직원 이름: Subhas, 나이: 25세
오류 발생: 나이는 반드시 18세보다 커야 합니다

코드 설명

위 예제에서 LowAgeError는 Exception 클래스를 상속받은 사용자 정의 예외입니다. __str__ 메서드를 재정의하여 예외 발생 시 출력될 오류 메시지를 지정했습니다.

Employee 클래스의 생성자에서는 나이가 18세 미만일 경우 raise LowAgeError를 통해 예외를 발생시킵니다. 첫 번째 객체(e1)는 나이가 25세이므로 정상적으로 생성되고 정보가 출력되지만, 두 번째 객체(e2)는 나이가 12세이므로 예외가 발생하여 except 블록에서 해당 오류 메시지를 출력하게 됩니다.

이처럼 사용자 정의 예외를 활용하면 비즈니스 규칙 위반 같은 상황을 명확하게 표현하고, 오류 처리 로직을 깔끔하게 분리할 수 있습니다.