본문 바로가기
IT/Python

Python - 예외 처리

by 최고영회 2018. 9. 18.
728x90
반응형
SMALL

예외처리는 try ~ except 문을 통해 처리 한다. 기본 문법은 아래와 같다.

try: 
   # do something
except EOFError:
  print('why did you do an eof on me?')
else:
  print('No exception')

다른 언어에서 처럼 예외클래스를 custom 하게 만들 수도 있다. 
마찬가지로 finally 를 이용하면 예외가 발생하더라도 안전하게 후처리를 할 수 있다.
class ShortInputException(Exception):
    '''A user-defined exception class'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    f = open('abc.txt')
    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 {} long, expected at least {}'.format(ex.length, ex.atleast))
else:
    print('No exception was rasied')
finally:
    if f:
        f.close()
위 예제 코드에서 본 것 처럼 except 절에 as 를 이용하면 짧은 이름으로 사용가능 하다. 

 java에서도 try-catch-finally 를 사용하지 않고 try-with 문을 이용하는 것 처럼 
python 에서도 동일하게 with 문을 이용할 수 있다.
with open('abc.txt') as f:
    for line in f:
        print(line)



728x90
반응형
LIST

'IT > Python' 카테고리의 다른 글

Python - Socket(Client) with struct (쉽게 테스트용 Client 만들기)  (0) 2018.09.11
Python - I/O, File I/O, pickle  (0) 2018.09.10
Python - Class  (0) 2018.09.07
Python - 자료구조  (0) 2018.08.30
Python - 함수  (0) 2018.08.27