본문 바로가기
파이썬

예외처리_파일읽기 예제로

by 혜룐 2015. 11. 10.
https://wikidocs.net/30
예외처리
방법 1
try:
...
except:
...
방법 2
try:
...except 발생에러(ex. ZeroDivisionError):
...
방법 3
try:
...except 발생에러(ex. ZeroDivisionError) as e:
print(e)
위는 예외처리 방법이다.
전에 파일 다루기 연습할때(
http://blog.cyworld.com/rhr0916/14559292 ), 특정 파일을 읽는 함수에 예외처리를 해야 더 견고해진다.
아래처럼 말이다.
def testRead(filename):
import os
pwd = os.getcwd()
try:
f = open(pwd+'/'+filename)
line = f.read()
except IOError as e:
print e
return
print line
exception이 발생했을때 에러메시지를 print 한 결과는 어떻게 나올까? 
프로그래밍한대로,
exception 메시지가 출력되고
, 끝까지 잘 수행되었다.
===== 1. read + write
===== 2. readline
[Errno 2] No such file or directory: '/data/script/python/blafileTest.log'
========== readline ==========
Programming is fun.
========== readlines ==========
VNone
ryNone
========== for readline ==========
You have to do it yourself...
Press ENTER or type command to continue
예외처리를 하지 않았다면,
아래처럼 IOError가 발생
했을 것이다.
왜냐? blafileTest.log 라는 파일이없기 때문이다.
그래서
정상적으로 수행되지 않는다.
Press ENTER or type command to continue
===== 1. read + write
===== 2. readline
Traceback (most recent call last):
File "handleFile.py", line 84, in<module>
testReadAndWriteMain()
File "handleFile.py", line 9, in testReadAndWriteMain
testRead('blafileTest.log')
File "handleFile.py", line 23, in testRead
f = open(pwd+'/'+filename)
IOError: [Errno 2] No such file or directory
: '/data/script/python/blafileTest.log'
shell returned 1