본문 바로가기
Computer & Program/python

[python] try-except (예외처리)

by TDRemon 2024. 2. 27.
반응형

안녕하세요. TDR입니다.

오늘은 python에서의 예외처리(try-except)에 대해서 간략히 정리해보겠습니다.

class Custom01Exception(Exception):
  def __init__(self, msg):
    super().__init__(msg)

class Custom02Exception(Exception):
  def __init__(self, msg):
    super().__init__(msg)

def step_01():
  try:
    raise Custom01Exception('Custom01Exception!')
  except Exception as msg:
    print('step01 exception : ' + str(msg))
    raise

def step_02():
  try:
    step_01()
  except Custom02Exception as msg:
    print('step02 exception : ' + str(msg))
    raise Custom02Exception("Custom02Exception!")

def step_03():
  try:
    step_02()
  except Custom01Exception as msg:
    print('step03 exception : ' + str(msg))

step_03()
# step01 exception : Custom01Exception!
# step03 exception : Custom01Exception!

코드 설명을 간략히 하면, 사용자가 임의로 생성한 Exception이 2개 있습니다. (Custom01Exception & Custom02Exception) 그리고 코드의 흐름은 가장 밑에 줄에서 step_03()을 호출하고 step_03()은 step_02()를 호출, step_02()는 step_01()을 호출합니다. 그리고 차례로 Exception을 발생시키는 구조입니다.

step_01()에서 Custom01Exception을 발생시켜 except에서 받고 있습니다. 보시면 except Exception으로 받기 때문에 모든 Exception을 받을 수 있습니다. 그리곤 내용을 출력한 후 raise 키워드를 통해 발생했던 Exception(Custom01Exception)을 그대로 위로 다시 전파하고 있습니다.

step_02()에서는 except Custom02Exception 이기 때문에 step_01()에서 전파시킨 Custom01Exception을 처리하지 못합니다. 하지만 최종 출력을 보면 step03도 출력된 것을 볼 수 있습니다. 이 말은 except에서 받지 못한 Exception은 자동으로 위로 전파한다는 것을 알 수 있습니다. (즉, 누군가 처리할 때까지 위로 전파)

step_03()에서는 except Custom01Exception 이기 때문에 전파된 Custom01Exception을 받을 수 있고, 그래서 내용을 출력하는 것을 볼 수 있습니다.

마지막으로 전체적인 try-except 흐름 및 python에서 사용되는 추가 내용을 정리해 보겠습니다. (Java에서는 try-catch와 같이 사용함)

class Custom01Exception(Exception):
  def __init__(self, msg):
    super().__init__(msg)
    
class Custom02Exception(Exception):
  def __init__(self, msg):
    super().__init__(msg)

def some_method():
  try:
    # raise 키워드를 통해 Custom02Exception 발생
    raise Custom02Exception('Custom02Exception!')
  except Custom01Exception:
    # Custom01Exception 만 받아서 처리
    # try에서 Custom02Exception을 발생 시켰기 때문에 여기는 안들어옴
  except Custom02Exception as msg:
    # try에서 Custom02Exception을 발생 시켰기 때문에 여기서 처리 가능
  except:
    # 위 except에서 처리가 안된 Exception이라면 여기서 모든 Exception을 받아서 처리 가능
    # except Exception과 동일. 모든 Exception은 Exception class를 상속해서 구현하기 때문
  else:
    # try에서 어떤 Exception도 발생하지 않았다면 여기로 진입
    # 즉, 정상적인 상황에서의 후속 처리를 여기서 하면 됨
  finally:
    # Exception이 발생했던 안했던 모든 코드는 최종적으로 여기로 지입
    
some_method()

참고로 CustomException을 생성하는 것을 보시면 일반적은 class 상속과 동일한 구조인 것을 알 수 있는데, 이건 Exception 클래스를 상속받아 나만의 Exception 클래스를 만드는 것이기 때문입니다. class 상속에 대한 자세한 내용은 아래 링크를 참조해 주세요.

 

[python] class(클래스) - 03

안녕하세요. TDR입니다. 2부에 이서 클래스 상속, 추상 클래스에 대해서 간략히 정리해 보겠습니다. [python] class(클래스) - 01 안녕하세요. TDR입니다. 이번에는 python에서 class를 어떻게 선언하고 어

tdremon.tistory.com

 

반응형

'Computer & Program > python' 카테고리의 다른 글

[python] Decorator(데코레이터) - 01  (0) 2024.02.29
[python] Assert(어설트)  (2) 2024.02.28
[python] class(클래스) - 03  (0) 2024.02.26
[python] class(클래스) - 02  (1) 2024.02.25
[python] class(클래스) - 01  (0) 2024.02.24

댓글