예외

Python의 객체 지향 프로그래밍

Alex Yarosh

Content Quality Analyst @ DataCamp

a = 1
a / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
a = [1,2,3]
a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a[5]
IndexError: list index out of range
a = 1
a + "Hello"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    a + "Hello"
TypeError: unsupported operand type(s) for +: /
'int' and 'str'
a = 1
a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a + b
NameError: name 'b' is not defined
Python의 객체 지향 프로그래밍

예외 처리

  • 예외가 발생해도 프로그램이 종료되지 않도록 합니다
  • try - except - finally:
try:
  # Try running some code

except ExceptionNameHere: # Run this code if ExceptionNameHere happens
except AnotherExceptionHere: #<-- multiple except blocks # Run this code if AnotherExceptionHere happens ...
finally: #<-- optional # Run this code no matter what
Python의 객체 지향 프로그래밍

예외 발생시키기

  • raise ExceptionNameHere('Error message here')
def make_list_of_ones(length):
    if length <= 0:
       raise ValueError("Invalid length!")  # <--- Will stop the program and raise an error
    return [1]*length   
make_list_of_ones(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    make_list_of_ones(-1)
  File "<stdin>", line 3, in make_list_of_ones
    raise ValueError("Invalid length!")
ValueError: Invalid length!
Python의 객체 지향 프로그래밍

예외는 클래스입니다

  • 표준 예외는 BaseException 또는 Exception을 상속합니다
    BaseException
    +-- Exception
        +-- ArithmeticError                     # <--- 
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              # <---
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Python의 객체 지향 프로그래밍

사용자 정의 예외

  • Exception 또는 그 하위 클래스를 상속합니다
  • 보통은 비어 있는 클래스입니다
class BalanceError(Exception): pass
class Customer:
   def __init__(self, name, balance):
    if balance < 0 :
       raise BalanceError("Balance has to be non-negative!")
    else:
       self.name, self.balance = name, balance

Python의 객체 지향 프로그래밍
cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    cust = Customer("Larry Torres", -100)
  File "script.py", line 6, in __init__
    raise BalanceError("Balance has to be non-negative!")
BalanceError: Balance has to be non-negative!
  • 예외로 인해 생성자가 중단됨 → 객체가 생성되지 않음
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Python의 객체 지향 프로그래밍

사용자 정의 예외 처리하기

try:
  cust = Customer("Larry Torres", -100)
except BalanceError:
  cust = Customer("Larry Torres", 0)
Python의 객체 지향 프로그래밍

Ayo berlatih!

Python의 객체 지향 프로그래밍

Preparing Video For Download...