구문 에러 (Syntax Error)
논리 에러 (Logical Error)
예외 (Exception)
4 + spam*3
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-c98bb92cdcac> in <module> ----> 1 4 + spam*3 NameError: name 'spam' is not defined
a = 10
b = 0
c = a / b
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-3-41671660f656> in <module> 1 a = 10 2 b = 0 ----> 3 c = a / b ZeroDivisionError: division by zero
def division():
for n in range(0, 5):
print(10.0 / n)
division()
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-4-726209e001ec> in <module> 3 print(10.0 / n) 4 ----> 5 division() <ipython-input-4-726209e001ec> in division() 1 def division(): 2 for n in range(0, 5): ----> 3 print(10.0 / n) 4 5 division() ZeroDivisionError: float division by zero
'2' + 2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-d2b23a1db757> in <module> ----> 1 '2' + 2 TypeError: must be str, not int
l = [1, 2]
print(l[2])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-08b5b9cc3f1f> in <module> 1 l = [1, 2] ----> 2 print(l[2]) IndexError: list index out of range
d = {"a": 1, "b": 2}
print(d['c'])
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-7-e0f66c508f6c> in <module> 1 d = {"a": 1, "b": 2} ----> 2 print(d['c']) KeyError: 'c'
a = open('aaa.txt')
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-8-ab28d2d0016c> in <module> ----> 1 a = open('aaa.txt') FileNotFoundError: [Errno 2] No such file or directory: 'aaa.txt'
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- 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 +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning
try:
(예외 발생 가능한) 일반적인 수행문들
except Exception:
예외가 발생하였을 때 수행되는 문들
else:
예외가 발생하지 않았을 때 수행되는 문들
finally:
예외 발생 유무와 관계없이 무조건 수행되는 문들
try:
print(1.0 / 0.0)
except ZeroDivisionError:
print('zero division error!!!')
zero division error!!!
#python3.x
def division():
for n in range(0, 5):
try:
print(10.0 / n)
except ZeroDivisionError as e:
print("ZeroDivisionError 발생")
print("-----" + str(e))
print("-----" + e.__str__())
print("-----" + str(e.__class__))
division()
ZeroDivisionError 발생 -----float division by zero -----float division by zero -----<class 'ZeroDivisionError'> 10.0 5.0 3.3333333333333335 2.5
def division():
for n in range(0, 5):
try:
print(10.0 / n)
else:
print("Success")
division()
File "<ipython-input-10-b3afe5cad960>", line 5 else: ^ SyntaxError: invalid syntax
#python3.x
try:
spam()
except NameError as e:
print('Error -', e)
Error - name 'spam' is not defined
#python3.x
def zero_division():
x = 1 / 0
try:
zero_division()
except ZeroDivisionError as e:
print('zero division error!!! -', e)
zero division error!!! - division by zero
#python3.x
def zero_division():
try:
x = 1 / 0
except ZeroDivisionError as e:
print('Inner - zero division error!!! -', e)
try:
zero_division()
except ZeroDivisionError as e:
print('Outer - zero division error!!! -', e)
Inner - zero division error!!! - division by zero
try:
spam()
print(1.0 / 0.0)
except:
print('Error')
Error
b = 0.0
name = 'aaa.txt'
try:
print(1.0 / b)
spam()
f = open(name, 'r')
'2' + 2
except NameError:
print('NameError !!!')
except ZeroDivisionError:
print('ZeroDivisionError !!!')
except (TypeError, IOError):
print('TypeError or IOError !!!')
else:
print('No Exception !!!')
finally:
print('Exit !!!')
ZeroDivisionError !!! Exit !!!
%ls t.txt
ls: t.txt: No such file or directory
#python3.x
import os
print(os.getcwd())
filename = 't.txt'
try:
f = open(filename, 'r')
except IOError as e:
print(e)
else:
a = float(f.readline())
try:
answer = 1.0 / a
except ZeroDivisionError as e:
print(e)
else:
print(answer)
finally:
print("Finally!!!")
f.close()
/Users/yhhan/git/python-e-learning/python3.6 [Errno 2] No such file or directory: 't.txt'
%ls a.txt
a.txt
%cat a.txt
0.0
#python3.x
import os
print(os.getcwd())
filename = 't.txt'
default_filename = 'a.txt'
try:
f = open(filename, 'r')
except IOError as e:
print(e)
f = open(default_filename, 'r')
a = float(f.readline())
try:
answer = 1.0 / a
except ZeroDivisionError as e:
print(e)
else:
print(answer)
finally:
print("Finally!!!")
f.close()
/Users/yhhan/git/python-e-learning/python3.6 [Errno 2] No such file or directory: 't.txt' float division by zero Finally!!!
def dosomething():
a = 1/0
try:
dosomething()
except ArithmeticError:
print("ArithmeticException occured")
ArithmeticException occured
def dosomething():
a = 1/0
try:
dosomething()
except ZeroDivisionError: # ZeroDivisionError는 이곳에서 잡힌다.
print("ZeroDivisionError occured")
except ArithmeticError: # FloatingPointError, OverflowError는 이곳에서 잡힌다.
print("ArithmeticException occured")
ZeroDivisionError occured
def dosomething():
a = 1/0
try:
dosomething()
except ArithmeticError:
print("ArithmeticException occured")
except ZeroDivisionError: # 이곳에서 ZeroDivisionError는 잡히지 않는다. ==> 잘못된 코드
print("ZeroDivisionError occured" )
ArithmeticException occured
class SquareSeq:
def __init__(self, n):
self.n = n
def __getitem__(self, k):
if k >= self.n or k < 0 :
raise IndexError # 첨자 범위를 벗어나면 IndexError 예외를 발생시킴
return k * k
def __len__(self):
return self.n
s = SquareSeq(10)
print(s[2], s[4])
for x in s: # IndexError가 발생하는 시점까지 반복한다
print(x,end=" ")
print(s[20]) # 첨자 범위가 넘었다
4 16 0 1 4 9 16 25 36 49 64 81
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-37-3da74b713108> in <module> 17 print(x,end=" ") 18 ---> 19 print(s[20]) # 첨자 범위가 넘었다 <ipython-input-37-3da74b713108> in __getitem__(self, k) 5 def __getitem__(self, k): 6 if k >= self.n or k < 0 : ----> 7 raise IndexError # 첨자 범위를 벗어나면 IndexError 예외를 발생시킴 8 return k * k 9 IndexError:
class Big(Exception):
pass
class Small(Big):
pass
def dosomething1():
x = Big()
raise x
def dosomething2():
raise Small()
for f in (dosomething1, dosomething2):
try:
f()
except Big:
print("Big Exception occurs!")
Big Exception occurs! Big Exception occurs!
#python3.x
def f():
raise Exception('message!!!')
try:
f()
except Exception as e:
print(e)
message!!!
#python3.x
a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('0으로 나누고 있습니다.')
a / b
except ArithmeticError as e:
print(e)
0으로 나누고 있습니다.
#python2.x
a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('0으로 나누고 있습니다.')
a / b
except ArithmeticError, v:
print v
0으로 나누고 있습니다.
참고 문헌: 파이썬(열혈강의)(개정판 VER.2), 이강성, FreeLec, 2005년 8월 29일