https://wikidocs.net/30
예외처리
방법 1
try:
...
except:
...
방법 2
try:
...except 발생에러(ex. ZeroDivisionError):
...
방법 3
try:
...except 발생에러(ex. ZeroDivisionError) as e:
print(e)
예외처리
방법 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()
import os
pwd = os.getcwd()
try:
f = open(pwd+'/'+filename)
line = f.read()
line = f.read()
except IOError as e:
print e
return
print line
exception이 발생했을때 에러메시지를 print 한 결과는 어떻게 나올까?
프로그래밍한대로,
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')
===== 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
shell returned 1
'파이썬' 카테고리의 다른 글
파이썬에서의 쓰레드 (0) | 2015.11.10 |
---|---|
인수 전달(sys.argv) , 스크립트 강제 종료 (sys.exit()) (0) | 2015.11.10 |
패키지 ( __init__.py , from 디렉터리 import 모듈, __all__ = ['모듈'] ) (0) | 2015.11.10 |
모듈만들고 불러오기_2 (sys.path.append(모듈절대경로)) (0) | 2015.11.10 |
파이썬 공부하기_모듈 만들고 불러보기 ( if __name__ == "__main__" ) (0) | 2015.11.10 |