1、python下异常如何处理:
1 #encoding=utf-8 2 3 """ 4 python遇到异常,程序直接运行 5 try: 6 "判断有可能抛出异常的代码" 7 print "haha" 8 except: 9 "异常下运行的代码" 10 else: 11 "运行没有异常时候的逻辑" 12 finally: 13 "不管try判断如何,该代码总会执行" 14 15 合理利用异常: 16 1、不得不用的地方采用异常; 17 2、正确使用异常:需要对异常进行捕获 18 比如:except IOError: 19 20 """ 21 22 a = [1, 2, 3, 4, 5, 6] 23 24 print a[4] 25 26 try: 27 print a[6] 28 except: 29 print u'哈哈' 30 31 print "继续可以到这里" 32 33 34 try: 35 print a[6] 36 except: 37 print "huhu" 38 else: 39 print "hoho" 40 finally: 41 print "hehe" 42 43 44 import urllib 45 sth_url = "http://wsdfsdf" 46 47 try: 48 d = urllib.urlopen(sth_url) 49 except: 50 print "出错了" 51 else: 52 content = d.read() 53 finally: 54 pass 55 #d.close() 56 57 """ 58 异常的note: 59 1、一个try对应一个except 60 2、使用python内置异常,来对应自身情况; 61 IOErro, IndexError 62 3、捕获异常的办法: 63 import logging 64 logger = logging.getLogger() 65 #logfile = 'excetion_demo.log' #log文件名 66 hdlr = logging.FileHandler('/tmp/sendlog.txt') 67 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') 68 hdlr.setFormatter(formatter) 69 logger.addHandler(hdlr) #logging绑定 70 logger.setLevel(logging.NOTSET) 71 72 73 import sys, logging 74 try: 75 d = urllib.urlopen("www.kdkdk.com") 76 except: 77 exc = sys.exc_info() 78 loggin.debug(exc[1] 79 print exc[1] 80 print exc 81 4、断言,assert 82 assert 表达式,"出错后抛出message" 83 assert 1>4, "expression Error" 84 先断言绝对不能发生的错误,然后在处理异常; 85 """ 86 87 """ 88 with用法:自动回收垃圾 89 #进入时,调用对象的__enter__ 90 #退出时,调用对象的__exit__函数 91 92 d = open('a', 'r') 93 d.read() 94 d.close() 95 96 with open('a', 'r') as d: 97 content = a.read() 98 """ 99 100 #with示例: 101 class sth(object): 102 def __init__(self, xixi): 103 self.a = xixi 104 105 def __enter__(self): 106 print u'哈哈, 进来了' 107 return self.a 108 109 def __exit__(self, type, value, traceback): 110 print u'哈哈,出去了' 111 112 with sth("gg") as s: 113 print s #s为__enter__返回值 114 115 """ 116 定义自己的异常类 117 """ 118 119 class myException(Exception): 120 def __init__(self, error, msg): 121 self.args = (error, msg) 122 self.error = error 123 self.msg = msg 124 125 try: 126 raise myException(1, "my exception") 127 except Exception as e: 128 print str(e)