参考链接:http://www.cnblogs.com/wupeiqi/articles/5017742.html
-----异常处理
1 names = ['alex','jack'] 2 data = {} 3 try: 4 # names[3] 5 # data['name'] 6 open("tes.txt") 7 # except Exception as e:#抓住所有错误,具体哪个错误自己揣测,一般不建议最开始用,不便于调试 8 # print("出错了",e) 9 except (KeyError,IndexError) as e :#合在一起写代码简单,但是不知道哪个出错了 10 print("没有这个Key",e)#适用场景:两种错误均采用统一的处理办法 11 12 except IndexError as e : 13 print("列表操作错误",e) 14 15 except Exception as e:#最后可以用 16 print("未知错误",e) 17 18 else: 19 print("一切正常") 20 21 finally: 22 print("不管有没有错,都执行") 23 24 #-------- value error------------------ 25 s1 = 'hello' 26 try: 27 int(s1) 28 except ValueError as e: 29 print ("粗错啦",e)
-----自定义异常
1 class AlexException(Exception): 2 3 def __init__(self, msg): 4 self.message = msg 5 6 # def __str__(self): 7 # return self.message 8 9 try: 10 raise AlexException('数据库连不上') 11 except AlexException as e: 12 print(e)