티스토리 뷰

카테고리 없음

파이썬 예외

철철22 2018. 8. 24. 10:02
반응형

예외처리(try ~ except)

def f(a, b): 

try: 

ifa andb: 

return(a * b) + (a / b) 

elifa: 

return '불능' 

else: 

return '부정' 

exceptErrorName: 

return '똑 바로 살아라'

 




예외발생시키기

   raise문에오류/예외의이름을넘길있다.
 





class ShortInputException(Exception):
    length = 0
    atleast = 0
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast



def exam():
	try:
		text = input('Enter something --> ')
		if len(text) <3:
			raise ShortInputException(len(text), 3)

	except EOFError:
		print( 'Why did you do an EOF on me?')
	except ShortInputException as ex:
		print('ShortInputException: The input was {0} long, expected at least {1}'.format(ex.length, ex.atleast))
	else:
		print('No exception was raised')


>>> exam()
Enter something --> a
ShortInputException: The input was 1 long, expected at least 3
>>> exam()
Enter something --> asdf
No exception was raised


반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함