Python 예외처리 구조

try:

예외 발생 가능성이 있는 문장

except [예외종류]:

예외 처리 문장

else:

예외가 발생하지 않은 경우, 수행할 문장

finally:

예외 발생 유무에 상관없이 try 블록 이후 수행할 문장


의도적으로 예외를 발생시켜야 하는 경우

raise

def RaiseErrorFunc():
     raise NameError
def PropagateError():
     try:RaiseErrorFunc()
     except:
          print "test"


예외가 발생할 경우를 기록

## Reading GPL Files
files_gpl = glob.glob('./GPLRaw/*.soft.gz')

## Recording parsing errors
files_err = open('parsing_GSM_err.txt', 'w')

for afile in files_gpl:
	print afile

	# Opening a gzip file
	try:
		file_gz = gzip.open(afile)
		s = 1/0
		file_gz.close()

	except Exception, e:
		files_err.write('%s' % e)
		files_err.write('\n')
files_err.close()

+ Recent posts