[Python응용] 11. 사용자 정의 예외 클래스 사용하기

raise구문과 사용자 정의 Exception 클래스를 사용하기

raise구문 정의

def raiseErrorFunc():
  raise NameError

try:
  raiseErroeFunc()
except:
  print("NameError is Catched")
NameError is Catched

사용자 정의 예외 클래스 사용

class NagativeDivisionError(Exception):
  def __init__(self, value):
    self.value = value

def positiveDivide(a, b):
  if (b < 0): # 0보다 적은 경우 NegativeDivisionError 발생ㅇ
    raise NagativeDivisionError(b)
  return a / b
try:
  ret = positiveDivide(10, -3)
  print('10 / 3 = {0}'.format(ret))
except NegativeDivisionError as e:
  print('Error = Second argument of PositiveDivide is', e.value)
except ZeroDivisionError as e:
  print('Error -', e.args[0])