구문 에러 (Syntax Error)
예외 (Exception)
4 + spam*3
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-6b1dfe582d2e> 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-1-d055e09331c6> in <module>() 1 a = 10 2 b = 0 ----> 3 c = a / b ZeroDivisionError: integer division or modulo by zero
def division():
for n in range(0, 5):
print 10.0 / n
division()
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-48-9618f69a4b0e> in <module>() 3 print 10.0 / n 4 ----> 5 division() <ipython-input-48-9618f69a4b0e> 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-3-4c6dd5170204> in <module>() ----> 1 '2' + 2 TypeError: cannot concatenate 'str' and 'int' objects
l = [1, 2]
print l[2]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-e36f806c83e5> 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-4-c5d228d3ae3c> in <module>() 1 d = {"a": 1, "b": 2} ----> 2 print d['c'] KeyError: 'c'
a = open('aaa.txt')
--------------------------------------------------------------------------- IOError Traceback (most recent call last) <ipython-input-6-971bbb0a7949> in <module>() ----> 1 a = open('aaa.txt') IOError: [Errno 2] No such file or directory: 'aaa.txt'
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StandardError | +-- BufferError | +-- ArithmeticError | | +-- FloatingPointError | | +-- OverflowError | | +-- ZeroDivisionError | +-- AssertionError | +-- AttributeError | +-- EnvironmentError | | +-- IOError | | +-- OSError | | +-- WindowsError (Windows) | | +-- VMSError (VMS) | +-- EOFError | +-- ImportError | +-- LookupError | | +-- IndexError | | +-- KeyError | +-- MemoryError | +-- NameError | | +-- UnboundLocalError | +-- ReferenceError | +-- RuntimeError | | +-- NotImplementedError | +-- SyntaxError | | +-- IndentationError | | +-- TabError | +-- SystemError | +-- TypeError | +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning
try:
(예외 발생 가능한) 일반적인 수행문들
except Exception:
예외가 발생하였을 때 수행되는 문들
else:
예외가 발생하지 않았을 때 수행되는 문들
finally:
예외 발생 유무와 관계없이 무조건 수행되는 문들
try:
print 1.0 / 0.0
except ZeroDivisionError:
print 'zero division error!!!'
zero division error!!!
def division():
for n in range(0, 5):
try:
print 10.0 / n
except ZeroDivisionError, msg:
print msg
division()
float division by zero 10.0 5.0 3.33333333333 2.5
def division():
for n in range(0, 5):
try:
print 10.0 / n
else:
print "Success"
division()
File "<ipython-input-49-e039cc968e23>", line 5 else: ^ SyntaxError: invalid syntax
try:
spam()
except NameError, msg:
print 'Error -', msg
Error - name 'spam' is not defined
try:
spam()
except NameError as msg:
print 'Error -', msg
Error - name 'spam' is not defined
def zero_division():
x = 1 / 0
try:
zero_division()
except ZeroDivisionError, msg:
print 'zero division error!!! -', msg
zero division error!!! - integer division or modulo by zero
def zero_division():
x = 1 / 0
try:
zero_division()
except ZeroDivisionError as msg:
print 'zero division error!!! -', msg
zero division error!!! - integer division or modulo 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 !!!
import os
print os.getcwd()
filename = 't.txt'
try:
f = open(filename, 'r')
except IOError, msg:
print msg
else:
a = float(f.readline())
try:
answer = 1.0 / a
except ZeroDivisionError, msg:
print msg
else:
print answer
finally:
print "Finally!!!"
f.close()
/Users/yhhan/git/python-e-learning 1.0 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,
print s[20] # 첨자 범위가 넘었다
4 16 0 1 4 9 16 25 36 49 64 81
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-f362c0e14e3a> in <module>() 13 for x in s: # IndexError가 발생하는 시점까지 반복한다 14 print x, ---> 15 print s[20] # 첨자 범위가 넘었다 <ipython-input-6-f362c0e14e3a> in __getitem__(self, k) 4 def __getitem__(self, k): 5 if k >= self.n or k < 0 : ----> 6 raise IndexError # 첨자 범위를 벗어나면 IndexError 예외를 발생시킴 7 return k * k 8 def __len__(self): 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 "Exception occurs!"
Exception occurs! Exception occurs!
def f():
raise Exception, 'message!!!'
try:
f()
except Exception, a:
print a
message!!!
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일