python下异常处理

时间:2021-05-15 06:15:48

1、python下异常如何处理:

 #encoding=utf-8

 """
python遇到异常,程序直接运行
try:
"判断有可能抛出异常的代码"
print "haha"
except:
"异常下运行的代码"
else:
"运行没有异常时候的逻辑"
finally:
"不管try判断如何,该代码总会执行" 合理利用异常:
1、不得不用的地方采用异常;
2、正确使用异常:需要对异常进行捕获
比如:except IOError: """ a = [1, 2, 3, 4, 5, 6] print a[4] try:
print a[6]
except:
print u'哈哈' print "继续可以到这里" try:
print a[6]
except:
print "huhu"
else:
print "hoho"
finally:
print "hehe" import urllib
sth_url = "http://wsdfsdf" try:
d = urllib.urlopen(sth_url)
except:
print "出错了"
else:
content = d.read()
finally:
pass
#d.close() """
异常的note:
1、一个try对应一个except
2、使用python内置异常,来对应自身情况;
IOErro, IndexError
3、捕获异常的办法:
import logging
logger = logging.getLogger()
#logfile = 'excetion_demo.log' #log文件名
hdlr = logging.FileHandler('/tmp/sendlog.txt')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr) #logging绑定
logger.setLevel(logging.NOTSET) import sys, logging
try:
d = urllib.urlopen("www.kdkdk.com")
except:
exc = sys.exc_info()
loggin.debug(exc[1]
print exc[1]
print exc
4、断言,assert
assert 表达式,"出错后抛出message"
assert 1>4, "expression Error"
先断言绝对不能发生的错误,然后在处理异常;
""" """
with用法:自动回收垃圾
#进入时,调用对象的__enter__
#退出时,调用对象的__exit__函数 d = open('a', 'r')
d.read()
d.close() with open('a', 'r') as d:
content = a.read()
""" #with示例:
class sth(object):
def __init__(self, xixi):
self.a = xixi def __enter__(self):
print u'哈哈, 进来了'
return self.a def __exit__(self, type, value, traceback):
print u'哈哈,出去了' with sth("gg") as s:
print s #s为__enter__返回值 """
定义自己的异常类
""" class myException(Exception):
def __init__(self, error, msg):
self.args = (error, msg)
self.error = error
self.msg = msg try:
raise myException(1, "my exception")
except Exception as e:
print str(e)