try\except\finally
标准内置except error: https://www.runoob.com/python/python-exceptions.html
(1)使用标准except输出error。finally语句一定会执行,引发异常后会跳出try语句继续执行下面代码。
# -*- coding: utf-8 -*-
import traceback
flag=True
file = "C:\\Users\\RSGIS201-4\\Desktop\\test1.csv"
while flag:
try:
flag = False
f = open(file)
print f
assert 1==2
except IOError,Argument:
print Argument
file = "C:\\Users\\RSGIS201-4\\Desktop\\test.csv"
flag=True
#使用traceback将错误信息输出到控制台和txt
traceback.print_exc()
f0 = open("C:\\Users\\RSGIS201-4\\Desktop\\1.txt", 'a')
traceback.print_exc(file=f0)
f0.flush()
f0.close()
# 使用logging将错误信息输出到控制台和txt
except AssertionError :
print "AssertionError"
finally:
print "先执行finay还是exce"
(2)自定义except。所有异常的基类都是BaseException.
class TooLongExceptin(): #自定义异常
"this is user's Exception for check the length of name "
def __init__(self, leng):
self.leng = leng
def __str__(self):
return "姓名长度是" + str(self.leng) + ",超过长度了"
name="dsvbailf"
try:
if len(name) > 4:
raise TooLongExceptin(len(name)) #自定义抛出异常
print "why?"
except TooLongExceptin,b: #捕捉异常
print b ##bTooLongExceptin的实例,print 会自动调用 __str__函数。