最常见的异常就是文件打开 时,找不到文件
try:
f = open(“file.txt”,”r”)
except IOError, e:
print e
然后就是命名空间异常,也就是没有定义这个变量或对象
try:
s = None
if s is None:
print "s 是空对象"
raise NameError #如果引发NameError异常,后面的代码将不能执行
print len(s)
except TypeError:
print "空对象没有长度"
还有就是违反运算法则的错误,两个例子
def divide(a, b):
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('Invalid inputs') from e
x , y = 7, 3
try:
result = divide(x, y)
except ValueError:
print('Invalid inputs')
else:
print('Result is %.1f' % result)
try:
s = "hello"
try:
print s[0] + s[1]
print s[0] - s[1]
except TypeError:
print "字符串不支持减法运算"
except:
print "异常"
文件的读写,可以用异常处理方式做的更完善
try:
f = open("hello.txt", "r")
try:
print f.read(5)
except:
print "读文件异常"
finally:
print "释放资源"
f.close()
except IOError:
print "文件不存在"
python中的常用异常如下:
AssertionError
AttributeError
IOError
ImportError
IndentationError
IndexError
KeyError
KeyboardInterrupt
NameError
SyntaxError
TypeError
UnboundLocalError
ValueError
参考
http://www.cnblogs.com/fnng/p/3518202.html
转载于:https://blog.51cto.com/matrix6ro/1893505