구문 에러 (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'
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
name = 'aaa.txt'
try:
f = open(name, 'r')
except IOError:
print 'cannot open', name
else:
print name, 'has', len(f.readline()), 'lines'
f.close()
cannot open aaa.txt
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/ipython float division by zero Finally!!!
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
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
for e in dir(__builtin__):
if e.endswith('Error') or e.endswith('Warning'):
print e
ArithmeticError AssertionError AttributeError BufferError BytesWarning DeprecationWarning EOFError EnvironmentError FloatingPointError FutureWarning IOError ImportError ImportWarning IndentationError IndexError KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError SyntaxError SyntaxWarning SystemError TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
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 "Big Exception = ", Big
Big Exception = <class '__main__.Big'> Big Exception = <class '__main__.Big'>
class MessageClass:
def __init__(self, message, dur):
self.message = message
self.duration = dur
def f():
raise Exception, 'message'
try:
f()
except Exception, a:
print a #에러발생
message
raise NameError
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-22-a586bde47246> in <module>() ----> 1 raise NameError NameError:
raise NameError('이름 예외')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-29-1cbe14fac70c> in <module>() ----> 1 raise NameError('이름 예외') NameError: 이름 예외
a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('0으로 나누고 있습니다.')
a / b
except ArithmeticError, v:
print v
0으로 나누고 있습니다.
a = 10
b = 0
try:
if b == 0:
raise ArithmeticError('0으로 나누고 있습니다.')
a / b
except ArithmeticError as e:
print e
0으로 나누고 있습니다.
assert 조건식, 메시지
# assert_test.py
a = 30
margin = 2 * 0.2
assert margin > 10, 'not enough margin %s' % margin
print a # assert의 조건식이 거짓이 되어 print a는 수행되지 않는다.
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-37-96778c4a816f> in <module>() 2 a = 30 3 margin = 2 * 0.2 ----> 4 assert margin > 10, 'not enough margin %s' % margin 5 print a # assert의 조건식이 거짓이 되어 print a는 수행되지 않는다. AssertionError: not enough margin 0.4
a = 30
margin = 2 * 0.2
try:
assert margin > 10, 'not enough margin %s' % margin
except AssertionError, msg:
print msg
not enough margin 0.4
a = 30
margin = 2 * 0.2
if __debug__:
assert margin > 10, 'not enough margin %s' % margin
--------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-19-0e9d5c09ff0f> in <module>() 3 margin = 2 * 0.2 4 if __debug__: ----> 5 assert margin > 10, 'not enough margin %s' % margin AssertionError: not enough margin 0.4