반응형
/************************************************************************************************
-- Title : [PY2.7.11] 예외 처리(Exception)
-- Reference : itsdong.com
-- Key word : 예외처리 예외 처리 try except else finally
************************************************************************************************/
-- utf-8
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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | # -*- coding: utf-8 -*- #-- 에러의 예 # FileNotFoundError : 파일이 없을 때 # ZeroDivisionError : 숫자를 0으로 나룰 때 # IndexError : 구문 오류 # EOF : 파일의 끝(읽을 내용이 없을 때) # -------------------------------------------- # -- try~except 추가 # -------------------------------------------- # -- TEST.py 저장 try: str = input('Input some string >> ') print(str) except EOFError: print ('There is no string.') # -- 실행(정상) D:\Python> python TEST.py Input some string >> 'hahaha' hahaha # -- 실행(exception) D:\Python> python TEST.py Input some string >> ^Z There is no string. # -------------------------------------------- # -- Exception 추가 및 else 처리 # -------------------------------------------- try: str = input('Input some string >> ') print(str) except EOFError: print ('There is no string.') # ^Z 눌러보소. except KeyboardInterrupt: print ('Canceled input string.') # ^C 눌러보소. else: print ('String you input is {}.'.format(str)) # -- 실행 D:\Python> python TEST.py Input some string >> ^C Cnaceled input string. D:\Python> python TEST.py Input some string >> 'ggg' String you input is ggg. # -------------------------------------------- # -- try~finally 추가 # 에러가 발생해도 finally문을 항상 수행 # -------------------------------------------- try: str = input('Input some string >> ') except EOFError: print ('There is no string.') # ^Z 눌러보소. except KeyboardInterrupt: print ('Canceled input string.') # ^C 눌러보소. else: print ('String you input is {}.'.format(str)) finally: print ('It has executed command.') # -- 실행(exception) D:\Python> python TEST.py Input some string >> ^Z It has executed command. # -------------------------------------------- # -- try~except~pass 추가 # 특정 에러가 발생해도 그냥 통과 # -------------------------------------------- try: fp = open('nofile.txt', 'r') except FileNotFoundError # 3.0 이상에서만 되나??? 에러남. pass # -------------------------------------------- # -- raise 추가 # 에러를 강제로 발생시키는 방법 # -------------------------------------------- class Flight: def fly(self): raise NotImplementedError # 내장 에러로 구현되지 않을 때 방생 class Plane(Flight) pass plane = Plane() plane.fly() # -------------------------------------------- # -- 사용자 예외 발생 시키기 # -------------------------------------------- class UserException(Exception): def __init__(self, length, minimum): self.length = length self.minimum = minimum try: txt = input("Input string >> ") if len(txt) < 5: raise UserException(len(txt), 5) except EOFError: # ^Z 눌러보소 print("No string!!") except KeyboardInterrupt: # ^C 눌러보소 print("Cancled input string!!") except UserException as uex: print("UserException: Input string size is {0}. Size bigger than min. {1}".format(uex.length, uex.minimum)) else: print("There is no excetion!!") ''' C:\python27\python.exe C:/python27/Project/20160425/test.py Input string >> "aaaaaa" There is no excetion!! C:\python27\python.exe C:/python27/Project/20160425/test.py Input string >> "aaa" UserException: Input string size is 3. Size bigger than min. 5 ''' | cs |
-- cp949
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 32 33 34 35 36 37 38 39 | # -*- coding: cp949 -*- import sys import time fp = None try: fp = open("text.txt", "r") while True: line = fp.readline() if len(line) == 0: break print(line) sys.stdout.flush() # 화면에 바로바로 출력하라. time.sleep(2) # S단위로 자라. except EOFError: # ^Z 눌러보소 print("There is no file to read!!") except KeyboardInterrupt: # 출력 중간에 ㅊㅌㅋ4+^C 눌러보소 print("User canceled!!") finally: # 예외 처리 후에도 실행되는 finally if fp: fp.close() print("File has been closed!!") ''' C:\python27\python.exe C:/python27/Project/20160425/test2.py 하나하면 할머니가 지팡이 들고서 덜덜덜 두울하면 두부장수 두부를 판다고 덜덜덜 File has been closed!! ''' | cs |
반응형