python exception的實例參考python
一、捕獲固定異常code
# -*- coding: utf-8 -*- while True: try: x = int(raw_input("please input a number:")) print x break except ValueError: print 'you not input a valid number try again!'
二、拋出異常以及分異常捕獲:orm
import os,sys # -*- coding: utf-8 -*- try: raise NameError('nameerror here') ff = open("myfile.txt") content = ff.readline() i = int(content.strip()) except IOError as e: print 'IO exception {0}__{1}'.format(e.errno,e.strerror) except ValueError: print 'please input a number' except: print 'unexcpted exception',sys.exc_info()[0] raise
三、用戶自定義異常ip
# -*- coding: utf-8 -*- #自定義異常 class MyError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) try: raise MyError(2*2) except MyError as e: print 'My exception occurred, value:', e.value