예외


In [1]:
open('no_such_file')


---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-1-35b25ef9beea> in <module>()
----> 1 open('no_such_file')

IOError: [Errno 2] No such file or directory: 'no_such_file'

In [3]:
5/0


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-3-67a69f72677d> in <module>()
----> 1 5/0

ZeroDivisionError: integer division or modulo by zero

In [4]:
[1,2][3]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-cbb6e8a4b213> in <module>()
----> 1 [1,2][3]

IndexError: list index out of range

In [5]:
'hello'.append('world')


---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-c2669b449811> in <module>()
----> 1 'hello'.append('world')

AttributeError: 'str' object has no attribute 'append'

예외 처리


In [8]:
try:
    open('no_such_file')
except IOError:
    print('그런 파일 없음')


그런 파일 없음

In [6]:
try:
    5/0
except IOError:
    print('... 파일 여는 거랑 무슨 상관?')


---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-d054e6c2f379> in <module>()
      1 try:
----> 2     5/0
      3 except IOError:
      4     print('... 파일 여는 거랑 무슨 상관?')

ZeroDivisionError: integer division or modulo by zero

In [9]:
try:
    5/0
except:
    print('다 잡아줄게')


다 잡아줄게

In [14]:
filename = 'hello_world.txt'
try:
    f = open(filename)
except IOError as ex:
    print(ex)
else:
    # try가 성공했을 때만 실행
    f.close()
    print('파일 열기 성공')


파일 열기 성공

In [17]:
filename = 'no_such_file.txt'
try:
    f = open(filename)
except IOError as ex:
    print(ex)
else:
    print('파일 열기 성공')
    f.close()
finally:
    # try가 성공하든 실패하든 무조건 실행된다
    print('파일명: {}'.format(filename))


[Errno 2] No such file or directory: 'no_such_file.txt'
파일명: no_such_file.txt

예외 전달


In [18]:
def get_lines(filename):
    try:
        f = open(filename)
    except IOError as e:
        raise # 발생한 예외를 위쪽(호출자)으로 전달
    
    return f.readlines()

filename = 'no_such_file.txt'
try:
    lines = get_lines(filename)
except IOError:
    print('그런 파일 없음: {}'.format(filename))


그런 파일 없음: no_such_file.txt

발생할 수 있는 예외가 여러 개인 경우


In [4]:
def safe_divide(a,b):
    try:
        result = a/b
    except ArithmeticError:
        print('수학 공부해야겠는데 ...')
        raise
    except TypeError as ex:
        print('숫자가 아닌 것으로 나눌 수 없습니다.')
        raise

    return result

In [8]:
safe_divide(3,2)


Out[8]:
1

In [6]:
safe_divide(5,0)


수학 공부해야겠는데 ...
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-f89c4d257bbf> in <module>()
----> 1 safe_divide(5,0)

<ipython-input-4-4db2376a84f8> in safe_divide(a, b)
      1 def safe_divide(a,b):
      2     try:
----> 3         result = a/b
      4     except ArithmeticError:
      5         print('수학 공부해야겠는데 ...')

ZeroDivisionError: integer division or modulo by zero

In [5]:
safe_divide(5,'a')


숫자가 아닌 것으로 나눌 수 없습니다.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-599eb170f148> in <module>()
----> 1 safe_divide(5,'a')

<ipython-input-4-4db2376a84f8> in safe_divide(a, b)
      1 def safe_divide(a,b):
      2     try:
----> 3         result = a/b
      4     except ArithmeticError:
      5         print('수학 공부해야겠는데 ...')

TypeError: unsupported operand type(s) for /: 'int' and 'str'

여러 개의 예외를 한번에 처리하기


In [9]:
def safe_divide(a,b):
    try:
        result = a/b
    except (ArithmeticError, TypeError) as e:
        print('나누기 오류!')
        raise
    else:
        return result

In [10]:
safe_divide(5,0)


나누기 오류!
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-10-f89c4d257bbf> in <module>()
----> 1 safe_divide(5,0)

<ipython-input-9-c40a8935a442> in safe_divide(a, b)
      1 def safe_divide(a,b):
      2     try:
----> 3         result = a/b
      4     except (ArithmeticError, TypeError) as e:
      5         print('나누기 오류!')

ZeroDivisionError: integer division or modulo by zero

예외 처리의 우선순위


In [26]:
def safe_divide(a,b):
    try:
        result = a/b
    except ZeroDivisionError:
        print('0으로 나눌 수 없습니다.')
    except ArithmeticError:
        print('수학 공부해야겠는데 ...')
    else:
        return result

In [27]:
safe_divide(5,0)


0으로 나눌 수 없습니다.

예외를 수동으로 발생시키기


In [28]:
raise ValueError


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-28-94ef6d30a139> in <module>()
----> 1 raise ValueError

ValueError: 

In [31]:
raise ArithmeticError


---------------------------------------------------------------------------
ArithmeticError                           Traceback (most recent call last)
<ipython-input-31-36d9a98b39c2> in <module>()
----> 1 raise ArithmeticError

ArithmeticError: 

In [ ]: